Ruotare una chiave

Questa pagina mostra come ruotare automaticamente o manualmente una chiave. Per maggiori informazioni informazioni sulla rotazione della chiave in generale, consulta Rotazione della chiave.

Ruoli obbligatori

Per ottenere le autorizzazioni di cui hai bisogno per ruotare le chiavi, chiedi all'amministratore di concederti i seguenti ruoli IAM sulla chiave:

Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso a progetti, cartelle e organizzazioni.

Questi ruoli predefiniti le autorizzazioni necessarie per ruotare le chiavi. Per vedere le autorizzazioni esatte obbligatorie, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per ruotare le chiavi sono necessarie le seguenti autorizzazioni:

  • Cambia la versione della chiave primaria: cloudkms.cryptoKeys.update
  • Modifica o disattiva la rotazione automatica: cloudkms.cryptoKeys.update
  • Crea nuova versione della chiave: cloudkms.cryptoKeyVersions.create
  • Disabilita le versioni precedenti della chiave: cloudkms.cryptoKeyVersions.update
  • Ricripta i dati:
    • cloudkms.cryptoKeyVersions.useToDecrypt
    • cloudkms.cryptoKeyVersions.useToEncrypt

Potresti anche riuscire a ottenere queste autorizzazioni con ruoli personalizzati altri ruoli predefiniti.

Un singolo utente con un ruolo personalizzato contenente tutte queste autorizzazioni può ruotare le chiavi e ricriptare i dati in autonomia. Utenti con il ruolo Amministratore Cloud KMS e il ruolo Autore crittografia/decrittografia CryptoKey Cloud KMS può collaborare per la rotazione e criptare i dati. Seguire il principio della privilegio minimo durante l'assegnazione ruoli. Per ulteriori dettagli, vedi Autorizzazioni e ruoli.

Quando ruoti una chiave, i dati criptati con versioni precedenti della chiave automaticamente ricriptata. Per saperne di più, vedi decriptare e ricriptare. La rotazione di una chiave non disattiva o disattiva automaticamente elimina tutte le versioni esistenti della chiave.

Configura la rotazione automatica

Per configurare la rotazione automatica durante la creazione di una nuova chiave:

Console

Quando utilizzi la console Google Cloud per creare una chiave, Cloud KMS imposta la periodo di rotazione e ora di rotazione successiva automaticamente. Puoi scegliere di utilizzare i valori predefiniti o specificare valori diversi.

Per specificare un periodo di rotazione e un'ora di inizio diversi, al momento della creazione la chiave, ma prima di fare clic sul pulsante Crea:

  1. Seleziona un'opzione per Periodo di rotazione della chiave.

  2. In corrispondenza di A partire dal, seleziona la data in cui vuoi che venga registrata la prima la rotazione. Puoi lasciare impostato il valore predefinito A partire da avvia la prima rotazione automatica un periodo di rotazione della chiave da quando per creare la chiave.

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima Installa o esegui l'upgrade alla versione più recente di Google Cloud CLI.

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • ROTATION_PERIOD: l'intervallo da Ruota la chiave, ad esempio 30d per ruotare la chiave ogni 30 giorni. La rotazione deve essere di almeno 1 giorno e al massimo 100 anni. Per ulteriori informazioni, vedi CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: il timestamp in corrispondenza del quale completare la prima rotazione, ad esempio "2023-01-01T01:02:03". Puoi omettere --next-rotation-time per pianificare la prima rotazione per 7 giorni dall'esecuzione dell'evento . Per ulteriori informazioni, vedi CryptoKey.nextRotationTime.

Per informazioni su tutti i flag e sui possibili valori, esegui il comando con --help flag.

C#

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo C# e installare l'SDK Cloud KMS C#.


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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Go e installa l'SDK Cloud KMS Go.

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

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo Java e installare l'SDK Java di Cloud KMS.

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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Cloud KMS.

//
// 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

Per eseguire questo codice, scopri innanzitutto come utilizzare PHP su Google Cloud e installa l'SDK PHP di Cloud KMS.

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

Per eseguire questo codice, configura prima un ambiente di sviluppo Python e installare l'SDK per Python di Cloud KMS.

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

Per eseguire questo codice, prima configura un ambiente di sviluppo Ruby e installa l'SDK Ruby di Cloud KMS.

# 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 questi esempi viene utilizzato curl come client HTTP per dimostrare l'uso dell'API. Per ulteriori informazioni sul controllo dell'accesso, vedi Accesso all'API Cloud KMS.

Per creare una chiave, utilizza 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"}'

Sostituisci quanto segue:

  • PURPOSE: il scopo della chiave.
  • ROTATION_PERIOD: l'intervallo da Ruota la chiave, ad esempio 30d per ruotare la chiave ogni 30 giorni. La rotazione deve essere di almeno 1 giorno e al massimo 100 anni. Per ulteriori informazioni, vedi CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: il timestamp in corrispondenza del quale completare la prima rotazione, ad esempio "2023-01-01T01:02:03". Puoi omettere --next-rotation-time per pianificare la prima rotazione per 7 giorni dall'esecuzione dell'evento . Per ulteriori informazioni, vedi CryptoKey.nextRotationTime.

Per configurare la rotazione automatica per una chiave esistente:

Console

  1. Vai alla pagina Gestione delle chiavi nella console Google Cloud.

    Vai alla pagina Gestione delle chiavi

  2. Fai clic sul nome del keyring che contiene la chiave per la quale vuoi aggiungere una pianificazione di rotazione.

  3. Fai clic sulla chiave a cui vuoi aggiungere una pianificazione di rotazione.

  4. Nell'intestazione, fai clic su Modifica periodo di rotazione.

  5. Nel prompt, scegli nuovi valori per Periodo di rotazione e Inizio on.

  6. Nel prompt, fai clic su Salva.

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima Installa o esegui l'upgrade alla versione più recente di Google Cloud CLI.

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • ROTATION_PERIOD: l'intervallo da Ruota la chiave, ad esempio 30d per ruotare la chiave ogni 30 giorni. La rotazione deve essere di almeno 1 giorno e al massimo 100 anni. Per ulteriori informazioni, vedi CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: il timestamp in corrispondenza del quale completare la prima rotazione, ad esempio "2023-01-01T01:02:03". Puoi omettere --next-rotation-time per pianificare la prima rotazione per 7 giorni dall'esecuzione dell'evento . Per ulteriori informazioni, vedi CryptoKey.nextRotationTime.

Per informazioni su tutti i flag e sui possibili valori, esegui il comando con --help flag.

C#

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo C# e installare l'SDK Cloud KMS C#.


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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Go e installa l'SDK Cloud KMS Go.

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

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo Java e installare l'SDK Java di Cloud KMS.

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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Cloud KMS.

//
// 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

Per eseguire questo codice, scopri innanzitutto come utilizzare PHP su Google Cloud e installa l'SDK PHP di Cloud KMS.

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

Per eseguire questo codice, configura prima un ambiente di sviluppo Python e installare l'SDK per Python di Cloud KMS.

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

Per eseguire questo codice, prima configura un ambiente di sviluppo Ruby e installa l'SDK Ruby di Cloud KMS.

# 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 questi esempi viene utilizzato curl come client HTTP per dimostrare l'uso dell'API. Per ulteriori informazioni sul controllo dell'accesso, vedi Accesso all'API Cloud KMS.

Per aggiornare una chiave, utilizza CryptoKey.patch :

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"}'

Sostituisci quanto segue:

  • ROTATION_PERIOD: l'intervallo da Ruota la chiave, ad esempio 30d per ruotare la chiave ogni 30 giorni. La rotazione deve essere di almeno 1 giorno e al massimo 100 anni. Per ulteriori informazioni, vedi CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: il timestamp in corrispondenza del quale completare la prima rotazione, ad esempio "2023-01-01T01:02:03". Puoi omettere --next-rotation-time per pianificare la prima rotazione per 7 giorni dall'esecuzione dell'evento . Per ulteriori informazioni, vedi CryptoKey.nextRotationTime.

Ruotare manualmente una chiave

Innanzitutto, crea una nuova versione della chiave:

Console

  1. Vai alla pagina Gestione delle chiavi nella console Google Cloud.

    Vai alla pagina Gestione delle chiavi

  2. Fai clic sul nome del keyring che contiene la chiave per la quale per creare una nuova versione della chiave.

  3. Fai clic sulla chiave per la quale creerai una nuova versione della chiave.

  4. Nell'intestazione, fai clic su Ruota.

  5. Nel messaggio, fai clic su Ruota per confermare.

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima Installa o esegui l'upgrade alla versione più recente di Google Cloud CLI.

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.

Le versioni della chiave sono numerate in sequenza.

Per informazioni su tutti i flag e sui possibili valori, esegui il comando con --help flag.

C#

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo C# e installare l'SDK Cloud KMS C#.


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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Go e installa l'SDK Cloud KMS Go.

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

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo Java e installare l'SDK Java di Cloud KMS.

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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Cloud KMS.

//
// 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

Per eseguire questo codice, scopri innanzitutto come utilizzare PHP su Google Cloud e installa l'SDK PHP di Cloud KMS.

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

Per eseguire questo codice, configura prima un ambiente di sviluppo Python e installare l'SDK per Python di Cloud KMS.

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

Per eseguire questo codice, prima configura un ambiente di sviluppo Ruby e installa l'SDK Ruby di Cloud KMS.

# 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 questi esempi viene utilizzato curl come client HTTP per dimostrare l'uso dell'API. Per ulteriori informazioni sul controllo dell'accesso, vedi Accesso all'API Cloud KMS.

Per ruotare manualmente una chiave, devi prima creare una nuova versione della chiave chiamando il metodo CryptoKeyVersions.create .

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

Questo comando crea una nuova versione della chiave, ma non la imposta come versione primaria.

Per impostare la nuova versione della chiave come primaria, consulta la sezione Impostazione di una versione esistente come o la versione della chiave primaria.

Se necessario, cripta nuovamente i dati criptati utilizzando la versione precedente della chiave.

Imposta una versione esistente come versione della chiave primaria

Per impostare una versione della chiave diversa come versione primaria di una chiave, aggiorna la chiave con le informazioni sulla nuova versione primaria. È necessario abilitare una versione della chiave prima di poterla configurare come versione principale.

Console

  1. Vai alla pagina Gestione delle chiavi nella console Google Cloud.

    Vai alla pagina Gestione delle chiavi

  2. Fai clic sul nome del keyring contenente la chiave la cui versione primaria che vuoi aggiornare.

  3. Fai clic sulla chiave di cui vuoi aggiornare la versione primaria.

  4. Nella riga corrispondente alla versione della chiave che vuoi impostare come primaria, fai clic su Mostra altro .

  5. Fai clic su Imposta versione principale nel menu.

  6. Nel messaggio di conferma, fai clic su Imposta come principale.

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima Installa o esegui l'upgrade alla versione più recente di Google Cloud CLI.

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • KEY_VERSION: il numero di versione della nuova versione della chiave primaria.

Per informazioni su tutti i flag e sui possibili valori, esegui il comando con --help flag.

C#

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo C# e installare l'SDK Cloud KMS C#.


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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Go e installa l'SDK Cloud KMS Go.

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

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo Java e installare l'SDK Java di Cloud KMS.

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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Cloud KMS.

//
// 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

Per eseguire questo codice, scopri innanzitutto come utilizzare PHP su Google Cloud e installa l'SDK PHP di Cloud KMS.

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

Per eseguire questo codice, prima configura un ambiente di sviluppo Ruby e installa l'SDK Ruby di Cloud KMS.

# 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

Per eseguire questo codice, configura prima un ambiente di sviluppo Python e installare l'SDK per Python di Cloud KMS.

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 questi esempi viene utilizzato curl come client HTTP per dimostrare l'uso dell'API. Per ulteriori informazioni sul controllo dell'accesso, vedi Accesso all'API Cloud KMS.

Modifica la versione della chiave primaria chiamando il metodo CryptoKey.updatePrimaryVersion .

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"}'

Sostituisci quanto segue:

  • PROJECT_ID: l'ID del progetto che contiene il keyring.
  • LOCATION: la località Cloud KMS del keyring.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • KEY_NAME: il nome della chiave.
  • KEY_VERSION: il numero di versione della nuova versione della chiave primaria.

Quando modifichi la versione della chiave primaria, la modifica in genere diventa coerente entro 1 minuto. Tuttavia, la propagazione di questa modifica può richiedere fino a tre ore casi eccezionali. Durante questo periodo, potrebbe essere utilizzata la versione principale precedente crittografare i dati. Per ulteriori informazioni, vedi Coerenza delle risorse di Cloud KMS.

Disattiva la rotazione automatica

Per disattivare la rotazione automatica per una chiave, cancella la pianificazione di rotazione della chiave:

Console

  1. Vai alla pagina Gestione delle chiavi nella console Google Cloud.

    Vai alla pagina Gestione delle chiavi

  2. Fai clic sul nome del keyring che contiene la chiave per la quale vuoi rimuovi la pianificazione della rotazione.

  3. Fai clic sulla chiave da cui vuoi rimuovere la pianificazione della rotazione.

  4. Nell'intestazione, fai clic su Modifica periodo di rotazione.

  5. Quando richiesto, fai clic sul campo Periodo di rotazione e seleziona Mai (rotazione manuale).

  6. Nel prompt, fai clic su Salva.

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima Installa o esegui l'upgrade alla versione più recente di Google Cloud CLI.

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.

Per informazioni su tutti i flag e sui possibili valori, esegui il comando con --help flag.

C#

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo C# e installare l'SDK Cloud KMS C#.


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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Go e installa l'SDK Cloud KMS Go.

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

Per eseguire questo codice, per prima cosa configura un ambiente di sviluppo Java e installare l'SDK Java di Cloud KMS.

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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Cloud KMS.

//
// 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

Per eseguire questo codice, scopri innanzitutto come utilizzare PHP su Google Cloud e installa l'SDK PHP di Cloud KMS.

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

Per eseguire questo codice, prima configura un ambiente di sviluppo Ruby e installa l'SDK Ruby di Cloud KMS.

# 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

Per eseguire questo codice, configura prima un ambiente di sviluppo Python e installare l'SDK per Python di Cloud KMS.

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 questi esempi viene utilizzato curl come client HTTP per dimostrare l'uso dell'API. Per ulteriori informazioni sul controllo dell'accesso, vedi Accesso all'API Cloud KMS.

Per aggiornare una chiave, utilizza CryptoKey.patch :

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}'

Per ulteriori dettagli su rotationPeriod e nextRotationTime, vedi keyRings.cryptoKeys

Ruotare una chiave esterna

Ruota una chiave esterna coordinata

Puoi configurare la rotazione automatica per funzioni simmetriche coordinate chiavi esterne. Puoi anche creare manualmente una nuova versione della chiave per le chiavi simmetriche chiavi esterne coordinate asimmetriche.

La rotazione o la creazione di una nuova versione della chiave fa sì che tutti i nuovi dati creati siano protetti a quella chiave per la crittografia con la nuova versione della chiave. Dati protetti con se una versione precedente della chiave non viene ricriptata. Di conseguenza, la chiave esterna gestore deve continuare a creare il materiale della chiave della versione precedente della chiave possono essere utilizzate.

Per creare una nuova versione della chiave per una chiave esterna coordinata, completa i seguenti passaggi:

Console

  1. Nella console Google Cloud, vai alla Gestione delle chiavi.

    Vai a Gestione delle chiavi

  2. Seleziona il keyring e poi la chiave.

  3. Fai clic su Crea versione. Un messaggio indica che la nuova versione della chiave sia in Cloud KMS che nell'EKM. Se vedi un Key path (Percorso chiave) o Key URI (URI chiave), la chiave selezionata non è coordinata chiave esterna.

  4. Per confermare che vuoi creare una nuova versione della chiave, fai clic su Crea dell'audiodescrizione.

La nuova versione della chiave viene visualizzata con lo stato In attesa di generazione. Per simmetri le versioni delle chiavi create manualmente non vengono impostate automaticamente come e la versione della chiave primaria. Puoi impostare la nuova versione della chiave come principale.

Interfaccia a riga di comando gcloud

Per creare una nuova versione della chiave simmetrica e impostarla come versione della chiave primaria, usa il comando kms keys versions create con il flag --primary:

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.

Per creare una nuova versione della chiave asimmetrica o creare una nuova chiave simmetrica diversa da quella della chiave primaria, usa il comando kms keys versions create:

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.

Ruota un Cloud EKM gestito manualmente tramite chiave VPC

Innanzitutto, ruota il materiale della chiave esterna nel gestore di chiavi esterno. Se questo genera un nuovo percorso della chiave, devi eseguire la rotazione o creare un nuovo Cloud EKM con il nuovo percorso della chiave. Per le chiavi di crittografia simmetriche, rotate la chiave Cloud EKM e specifica il nuovo percorso della chiave dalla chiave esterna responsabile. Per le chiavi asimmetriche, crea una nuova versione della chiave e specifica la nuova chiave del tuo percorso di apprendimento.

La rotazione o la creazione di una nuova versione della chiave fa sì che tutti i nuovi dati creati siano protetti a quella chiave per la crittografia con la nuova versione della chiave. Dati protetti con se una versione precedente della chiave non viene ricriptata. Di conseguenza, la chiave esterna gestore deve continuare a creare il materiale della chiave della versione precedente della chiave possono essere utilizzate.

Se il materiale della chiave nel sistema esterno di gestione delle chiavi del partner non cambia, ma la chiave modifiche al percorso, puoi aggiornare il campo senza ruotare la chiave.

Console

  1. Nella console Google Cloud, vai alla Gestione delle chiavi.

    Vai a Gestione delle chiavi

  2. Seleziona il keyring e poi la chiave.

  3. Fai clic su Ruota la chiave.

  4. In Percorso chiave, inserisci il percorso della chiave per la nuova versione.

  5. Fai clic su Ruota la chiave per confermare.

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima Installa o esegui l'upgrade alla versione più recente di Google Cloud CLI.

Per creare una nuova versione della chiave simmetrica e impostarla come versione della chiave primaria, usa il comando kms keys versions create con il flag --primary:

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • EXTERNAL_KEY_PATH: il percorso del nuovo server esterno e la versione della chiave.

Per creare una nuova versione della chiave asimmetrica o creare una nuova chiave simmetrica diversa da quella della chiave primaria, usa il comando kms keys versions create:

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • EXTERNAL_KEY_PATH: il percorso del nuovo server esterno e la versione della chiave.

Per informazioni su tutti i flag e sui possibili valori, esegui il comando con --help flag.

Dopo aver creato la versione della chiave, puoi utilizzarla come faresti e utilizzare qualsiasi altra versione della chiave Cloud KMS.

Ruotare un Cloud EKM gestito manualmente tramite chiave internet

Innanzitutto, ruota il materiale della chiave esterna nel gestore di chiavi esterno. Se questo restituisce un nuovo URI, devi eseguire la rotazione o creare una nuova chiave Cloud EKM con il nuovo URI. Per le chiavi di crittografia simmetriche, rotate la chiave Cloud EKM e specifica il nuovo URI della chiave dalla chiave esterna responsabile. Per le chiavi asimmetriche, crea una nuova versione della chiave e specifica la nuova chiave URI.

La rotazione o la creazione di una nuova versione della chiave fa sì che tutti i nuovi dati creati siano protetti a quella chiave per la crittografia con la nuova versione della chiave. Dati protetti con se una versione precedente della chiave non viene ricriptata. Di conseguenza, la chiave esterna gestore deve continuare a creare il materiale della chiave della versione precedente della chiave possono essere utilizzate.

Se il materiale della chiave nel sistema esterno di gestione delle chiavi del partner non cambia, ma l'URI modifiche, puoi aggiornare il codice esterno della chiave URI senza ruotare la chiave.

Console

  1. Nella console Google Cloud, vai alla Gestione delle chiavi.

    Vai a Gestione delle chiavi

  2. Seleziona il keyring e poi la chiave.

  3. Seleziona Ruota chiave per le chiavi simmetriche o Crea versione per e asimmetriche.

  4. Inserisci il nuovo URI della chiave, quindi seleziona Ruota chiave per le chiavi simmetriche oppure Crea la versione per le chiavi asimmetriche.

La nuova versione della chiave diventa la versione primaria.

Interfaccia a riga di comando gcloud

Per creare una nuova versione della chiave simmetrica e impostarla come versione della chiave primaria, usa il comando kms keys versions create con il flag --primary:

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • EXTERNAL_KEY_URI: l'URI della chiave del nuovo server esterno e la versione della chiave.

Per creare una nuova versione della chiave asimmetrica o creare una nuova chiave simmetrica diversa da quella della chiave primaria, usa il comando kms keys versions create:

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

Sostituisci quanto segue:

  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • EXTERNAL_KEY_URI: l'URI della chiave del nuovo server esterno e la versione della chiave.