Eliminazione e ripristino delle versioni delle chiavi

Questa pagina mostra come pianificare una versione della chiave di Cloud Key Management Service per la distruzione permanente. Quando elimini una versione della chiave, il materiale della chiave viene eliminato, ma gli altri dettagli come il nome e il numero della versione non vengono eliminati. Dopo aver eliminato una chiave, i dati criptati con la chiave non possono essere decriptati.

Quando invii una richiesta per eliminare una versione della chiave, l'eliminazione avviene dopo 24 ore per impostazione predefinita. Puoi annullare la richiesta di eliminazione ripristinando la versione della chiave.

La chiave rimane in stato pianificata per l'eliminazione per 24 ore. Puoi modificare questa durata predefinita al momento della creazione della chiave.

Puoi anche gestire l'accesso alla chiave utilizzando Identity and Access Management (IAM). Le operazioni IAM sono coerenti in pochi secondi. Per ulteriori informazioni, consulta la sezione Utilizzare IAM.

Puoi anche disattivare temporaneamente una versione della chiave.

Nel resto di questo argomento, la pianificazione dell'eliminazione di una chiave viene definita come eliminazione della chiave, anche se l'eliminazione non è immediata.

Distruzione della versione di una chiave

Puoi eliminare una versione della chiave abilitata o disabilitata.

Console

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

    Vai a Key Management

  2. Seleziona la casella accanto alla versione della chiave di cui vuoi pianificare la distruzione.

  3. Fai clic su Elimina nell'intestazione.

  4. Nel prompt di conferma, inserisci il nome della chiave e fai clic su Pianifica distruzione.

gcloud

Per utilizzare Cloud KMS, dalla riga di comando, devi prima installare o eseguire l'upgrade alla versione più recente di Google Cloud CLI.

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

Sostituisci quanto segue:

  • KEY_VERSION: il numero di versione della versione della chiave che vuoi eliminare.
  • KEY_NAME: il nome della chiave per la quale vuoi eliminare una versione della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la posizione Cloud KMS del keyring.

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

C#

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


using Google.Cloud.Kms.V1;

public class DestroyKeyVersionSample
{
    public CryptoKeyVersion DestroyKeyVersion(
      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 version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        CryptoKeyVersion result = client.DestroyCryptoKeyVersion(keyVersionName);

        // Return the result.
        return result;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// destroyKeyVersion marks a specified key version for deletion. The key can be
// restored if requested within 24 hours.
func destroyKeyVersion(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/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.DestroyCryptoKeyVersionRequest{
		Name: name,
	}

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

Java

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

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

public class DestroyKeyVersion {

  public void destroyKeyVersion() 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";
    destroyKeyVersion(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Schedule destruction of the given key version.
  public void destroyKeyVersion(
      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 key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Destroy the key version.
      CryptoKeyVersion response = client.destroyCryptoKeyVersion(keyVersionName);
      System.out.printf("Destroyed key version: %s%n", response.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 version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function destroyKeyVersion() {
  const [version] = await client.destroyCryptoKeyVersion({
    name: versionName,
  });

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

return destroyKeyVersion();

PHP

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

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

function destroy_key_version(
    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 version name.
    $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Call the API.
    $destroyedVersion = $client->destroyCryptoKeyVersion($keyVersionName);
    printf('Destroyed key version: %s' . PHP_EOL, $destroyedVersion->getName());

    return $destroyedVersion;
}

Python

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

from google.cloud import kms

def destroy_key_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.CryptoKeyVersion:
    """
    Schedule destruction of the given key version.

    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 version to destroy (e.g. '1').

    Returns:
        CryptoKeyVersion: The version.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    # Call the API.
    destroyed_version = client.destroy_crypto_key_version(
        request={"name": key_version_name}
    )
    print(f"Destroyed key version: {destroyed_version.name}")
    return destroyed_version

Ruby

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Ruby e installare 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 key version name.
key_version_name = client.crypto_key_version_path project:            project_id,
                                                  location:           location_id,
                                                  key_ring:           key_ring_id,
                                                  crypto_key:         key_id,
                                                  crypto_key_version: version_id

# Call the API.
destroyed_version = client.destroy_crypto_key_version name: key_version_name
puts "Destroyed key version: #{destroyed_version.name}"

API

Questi esempi utilizzano curl come client HTTP per dimostrare che utilizzano l'API. Per ulteriori informazioni sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

Distruggi una versione della chiave chiamando il metodo CryptoKeyVersions.delete.

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

Quando invii la richiesta di eliminazione, lo stato della versione della chiave diventa pianificata per l'eliminazione. Una volta trascorsa la durata pianificata per l'eliminazione della chiave, lo stato della versione della chiave diventa Eliminato. Ciò significa che l'eliminazione logica del materiale della chiave dai sistemi attivi è iniziata e il materiale della chiave non può essere recuperato dal cliente. Il materiale della chiave può rimanere nei sistemi Google per un massimo di 45 giorni dal momento dell'eliminazione pianificata.

Per ricevere un avviso quando viene pianificata l'eliminazione di una versione della chiave, consulta la pagina relativa all'utilizzo di Cloud Monitoring con Cloud KMS.

Le versioni della chiave eliminata non vengono fatturate.

Eliminazione delle chiavi esterne

Per rimuovere definitivamente l'associazione tra una chiave Cloud EKM e una chiave esterna, puoi eliminare la versione della chiave. Una volta trascorso il periodo pianificata per l'eliminazione, la chiave viene eliminata. Dopo aver eliminato la versione della chiave, non puoi più criptare i dati o decriptare i dati criptati con la versione della chiave Cloud EKM.

L'eliminazione di una versione di chiave gestita manualmente in Cloud KMS non modifica la chiave nel gestore di chiavi esterno. Ti consigliamo di eliminare prima la chiave o la versione della chiave in Google Cloud. Dopo aver eliminato la versione della chiave EKM di Cloud, puoi eliminare il materiale della chiave nel gestore di chiavi esterno.

L'eliminazione di una versione di chiave esterna coordinata in Cloud KMS elimina prima la versione della chiave in Google Cloud, quindi invia una richiesta di eliminazione all'EKM per eliminare il materiale della chiave esterna.

Ripristinare una versione della chiave

Durante il periodo in cui lo stato di una versione della chiave è pianificata per l'eliminazione, puoi ripristinare la versione della chiave inviando una richiesta di ripristino.

Console

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

    Vai alla pagina Key Management

  2. Fai clic sul nome del keyring contenente la chiave di cui verrà ripristinata la versione della chiave.

  3. Fai clic sulla chiave di cui vuoi ripristinare la versione della chiave.

  4. Seleziona la casella accanto alla versione della chiave che vuoi ripristinare.

  5. Fai clic su Ripristina nell'intestazione.

  6. Nella richiesta di conferma, fai clic su Ripristina.

gcloud

Per utilizzare Cloud KMS, dalla riga di comando, devi prima installare o eseguire l'upgrade alla versione più recente di Google Cloud CLI.

gcloud kms keys versions restore key-version \
    --key key \
    --keyring key-ring \
    --location location

Sostituisci key-version con la versione della chiave da ripristinare. Sostituisci key con il nome della chiave. Sostituisci key-ring con il nome del keyring in cui si trova la chiave. Sostituisci location con la località di Cloud KMS per il keyring.

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

C#

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


using Google.Cloud.Kms.V1;

public class RestoreKeyVersionSample
{
    public CryptoKeyVersion RestoreKeyVersion(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 version name.
        CryptoKeyVersionName cryptoKeyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        CryptoKeyVersion result = client.RestoreCryptoKeyVersion(cryptoKeyVersionName);

        // Return the result.
        return result;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// restoreKeyVersion attempts to recover a key that has been marked for
// destruction in the past 24h.
func restoreKeyVersion(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/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.RestoreCryptoKeyVersionRequest{
		Name: name,
	}

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

Java

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

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

public class RestoreKeyVersion {

  public void restoreKeyVersion() 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";
    restoreKeyVersion(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Schedule destruction of the given key version.
  public void restoreKeyVersion(
      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 key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Restore the key version.
      CryptoKeyVersion response = client.restoreCryptoKeyVersion(keyVersionName);
      System.out.printf("Restored key version: %s%n", response.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 version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function restoreKeyVersion() {
  const [version] = await client.restoreCryptoKeyVersion({
    name: versionName,
  });

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

return restoreKeyVersion();

PHP

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

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

function restore_key_version(
    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 version name.
    $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Call the API.
    $restoredVersion = $client->restoreCryptoKeyVersion($keyVersionName);
    printf('Restored key version: %s' . PHP_EOL, $restoredVersion->getName());

    return $restoredVersion;
}

Python

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

from google.cloud import kms

def restore_key_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.CryptoKeyVersion:
    """
    Restore a key version scheduled for destruction.

    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 version to use (e.g. '1').

    Returns:
        CryptoKeyVersion: Restored Cloud KMS key version.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    # Call the API.
    restored_version = client.restore_crypto_key_version(
        request={"name": key_version_name}
    )
    print(f"Restored key version: {restored_version.name}")
    return restored_version

Ruby

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Ruby e installare 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 key version name.
key_version_name = client.crypto_key_version_path project:            project_id,
                                                  location:           location_id,
                                                  key_ring:           key_ring_id,
                                                  crypto_key:         key_id,
                                                  crypto_key_version: version_id

# Call the API.
restored_version = client.restore_crypto_key_version name: key_version_name
puts "Restored key version: #{restored_version.name}"

API

Questi esempi utilizzano curl come client HTTP per dimostrare che utilizzano l'API. Per ulteriori informazioni sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

Ripristina una versione della chiave chiamando il metodo CryptoKeyVersions.restore.

curl "https://cloudkms.googleapis.com/v1/projects/project-id/locations/location-id/keyRings/key-ring-id/cryptoKeys/crypto-key-id/cryptoKeyVersions/version-id:restore" \
    --request "POST" \
    --header "authorization: Bearer token"

Al termine della richiesta di ripristino, lo stato della versione della chiave diventa Disattivato. Devi attivare la chiave per poterla utilizzare.

Autorizzazioni IAM richieste

Per eliminare una versione della chiave, il chiamante ha bisogno dell'autorizzazione IAM cloudkms.cryptoKeyVersions.destroy sulla chiave, sul keyring, sul progetto, sulla cartella o sull'organizzazione.

Per ripristinare una versione della chiave, il chiamante ha bisogno dell'autorizzazione cloudkms.cryptoKeyVersions.restore.

entrambe le autorizzazioni vengono concesse al ruolo Amministratore Cloud KMS (roles/cloudkms.admin).

Cronologia di eliminazione

Cloud KMS si impegna a eliminare il materiale della chiave del cliente da tutta l'infrastruttura di Google entro 45 giorni dal momento dell'eliminazione pianificata. Questo include la rimozione dei dati sia dai sistemi attivi sia dai backup dei data center. Altri dati dei clienti sono soggetti alle tempistiche di eliminazione standard di Google Cloud di 180 giorni.