Creazione di chiavi di crittografia simmetriche

In questa pagina viene mostrato come creare una chiave di crittografia simmetrica.

Puoi anche creare una chiave asimmetrica, una chiave Cloud HSM o una chiave di Cloud External Key Manager.

Panoramica

Quando crei una chiave, la aggiungi a un keyring in una determinata posizione di Google Cloud. Puoi creare un nuovo keyring o utilizzarne uno esistente. In questo argomento, creerai un nuovo keyring e vi aggiungerai una nuova chiave.

Creazione di un keyring

Segui questi passaggi per creare un keyring per la nuova chiave. Se vuoi utilizzare un keyring esistente, puoi creare una chiave.

Console

  1. Vai alla pagina Gestione chiavi in Google Cloud Console.

    Vai alla pagina Gestione delle chiavi

  2. Fai clic su Crea keyring.

  3. Nel campo Nome keyring, inserisci il nome da assegnare al keyring.

  4. Nel menu a discesa Posizione keyring, seleziona una località come "us-east1".

  5. Fai clic su Crea.

gcloud CLI

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 keyrings create key-ring \
    --location location

Sostituisci key-ring con un nome per il keyring. Sostituisci location con la posizione di Cloud KMS per il keyring e le relative chiavi.

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.Api.Gax.ResourceNames;
using Google.Cloud.Kms.V1;

public class CreateKeyRingSample
{
    public KeyRing CreateKeyRing(
      string projectId = "my-project", string locationId = "us-east1",
      string id = "my-key-ring")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent location name.
        LocationName locationName = new LocationName(projectId, locationId);

        // Build the key ring.
        KeyRing keyRing = new KeyRing { };

        // Call the API.
        KeyRing result = client.CreateKeyRing(locationName, id, keyRing);

        // Return the result.
        return result;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// createKeyRing creates a new ring to store keys on KMS.
func createKeyRing(w io.Writer, parent, id string) error {
	// parent := "projects/PROJECT_ID/locations/global"
	// id := "my-key-ring"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %v", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateKeyRingRequest{
		Parent:    parent,
		KeyRingId: id,
	}

	// Call the API.
	result, err := client.CreateKeyRing(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key ring: %v", err)
	}
	fmt.Fprintf(w, "Created key ring: %s\n", result.Name)
	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.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;
import java.io.IOException;

public class CreateKeyRing {

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

  // Create a new key ring.
  public void createKeyRing(String projectId, String locationId, 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 and location.
      LocationName locationName = LocationName.of(projectId, locationId);

      // Build the key ring to create.
      KeyRing keyRing = KeyRing.newBuilder().build();

      // Create the key ring.
      KeyRing createdKeyRing = client.createKeyRing(locationName, id, keyRing);
      System.out.printf("Created key ring %s%n", createdKeyRing.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 id = 'my-key-ring';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

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

// Build the parent location name
const locationName = client.locationPath(projectId, locationId);

async function createKeyRing() {
  const [keyRing] = await client.createKeyRing({
    parent: locationName,
    keyRingId: id,
  });

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

return createKeyRing();

PHP

Per eseguire questo codice, consulta prima l'articolo sull'utilizzo di PHP su Google Cloud e installa l'SDK PHP Cloud KMS.

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\KeyRing;

function create_key_ring(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $id = 'my-key-ring'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent location name.
    $locationName = $client->locationName($projectId, $locationId);

    // Build the key ring.
    $keyRing = new KeyRing();

    // Call the API.
    $createdKeyRing = $client->createKeyRing($locationName, $id, $keyRing);
    printf('Created key ring: %s' . PHP_EOL, $createdKeyRing->getName());

    return $createdKeyRing;
}

Python

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

def create_key_ring(project_id, location_id, key_ring_id):
    """
    Creates a new key ring in Cloud KMS

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the key ring to create (e.g. 'my-key-ring').

    Returns:
        KeyRing: Cloud KMS key ring.

    """

    # Import the client library.
    from google.cloud import kms

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

    # Build the parent location name.
    location_name = f'projects/{project_id}/locations/{location_id}'

    # Build the key ring.
    key_ring = {}

    # Call the API.
    created_key_ring = client.create_key_ring(
        request={'parent': location_name, 'key_ring_id': key_ring_id, 'key_ring': key_ring})
    print('Created key ring: {}'.format(created_key_ring.name))
    return created_key_ring

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"
# id = "my-key-ring"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent location name.
location_name = client.location_path project: project_id, location: location_id

# Build the key ring.
key_ring = {}

# Call the API.
created_key_ring = client.create_key_ring parent: location_name, key_ring_id: id, key_ring: key_ring
puts "Created key ring: #{created_key_ring.name}"

API

In questi esempi viene utilizzato curl come client HTTP per dimostrare l'utilizzo dell'API. Per maggiori informazioni sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

curl "https://cloudkms.googleapis.com/v1/projects/project-id/locations/location-id/keyRings?key_ring_id=key-ring-id" \
    --request "POST" \
    --header "authorization: Bearer token"

Consulta la documentazione dell'API KeyRing.create per ulteriori informazioni.

Crea una chiave

Segui questi passaggi per creare una chiave di crittografia simmetrica sul keyring e sulla posizione specificati.

Console

  1. Vai alla pagina Gestione chiavi in Google Cloud Console.

    Vai alla pagina Gestione delle chiavi

  2. Fai clic sul nome del keyring per cui vuoi creare una chiave.

  3. Fai clic su Crea chiave.

  4. In Che tipo di chiave vuoi creare?, scegli Chiave generata.

  5. Nel campo Nome chiave, inserisci il nome della chiave.

  6. Fai clic sul menu a discesa Livello di protezione e seleziona Software.

  7. Fai clic sul menu a discesa Finalità e seleziona Crittografia/decriptazione simmetrica.

  8. Accetta i valori predefiniti per Periodo di rotazione e A partire dal giorno.

  9. Fai clic su Crea.

gcloud CLI

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 create key \
    --keyring key-ring \
    --location location \
    --purpose "encryption"

Sostituisci key con il nome della chiave. Sostituisci key-ring con il nome del keyring in cui si troverà la chiave. Sostituisci location con la posizione di 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 CreateKeySymmetricEncryptDecryptSample
{
    public CryptoKey CreateKeySymmetricEncryptDecrypt(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-symmetric-encryption-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

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

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

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

        // Return the result.
        return result;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
// on Cloud KMS.
func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-symmetric-encryption-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %v", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %v", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	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.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import java.io.IOException;

public class CreateKeySymmetricEncryptDecrypt {

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

  // Create a new key that is used for symmetric encryption and decryption.
  public void createKeySymmetricEncryptDecrypt(
      String projectId, String locationId, String keyRingId, String id) throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Build the symmetric key to create.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created symmetric key %s%n", createdKey.getName());
    }
  }
}

Node.js

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-symmetric-encryption-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

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

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

async function createKeySymmetricEncryptDecrypt() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
      },
    },
  });

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

return createKeySymmetricEncryptDecrypt();

PHP

Per eseguire questo codice, consulta prima l'articolo sull'utilizzo di PHP su Google Cloud e installa l'SDK PHP Cloud KMS.

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\Cloud\Kms\V1\KeyManagementServiceClient;

function create_key_symmetric_encrypt_decrypt(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-symmetric-key'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
        );

    // Call the API.
    $createdKey = $client->createCryptoKey($keyRingName, $id, $key);
    printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

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

def create_key_symmetric_encrypt_decrypt(project_id, location_id, key_ring_id, key_id):
    """
    Creates a new symmetric encryption/decryption key in Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to create (e.g. 'my-symmetric-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Import the client library.
    from google.cloud import kms

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

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
    key = {
        'purpose': purpose,
        'version_template': {
            'algorithm': algorithm,
        }
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={'parent': key_ring_name, 'crypto_key_id': key_id, 'crypto_key': key})
    print('Created symmetric key: {}'.format(created_key.name))
    return created_key

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"
# id          = "my-symmetric-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:          :ENCRYPT_DECRYPT,
  version_template: {
    algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created symmetric key: #{created_key.name}"

API

In questi esempi viene utilizzato curl come client HTTP per dimostrare l'utilizzo dell'API. Per maggiori informazioni sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

Per creare una chiave, utilizza il metodo CryptoKey.create:

curl "https://cloudkms.googleapis.com/v1/projects/project-id/locations/location-id/keyRings/key-ring-id/cryptoKeys?crypto_key_id=crypto-key-id" \
    --request "POST" \
    --header "authorization: Bearer token" \
    --header "content-type: application/json" \
    --data '{"purpose": "purpose"}'

Sostituisci purpose con lo scopo della chiave. Per i valori delle finalità consentite, consulta CryptoKeyPurpose.

Impostare un periodo di rotazione delle chiavi e un'ora di inizio

Puoi creare una chiave con un periodo di rotazione specificato, ovvero il tempo che intercorre tra il momento in cui vengono generate automaticamente le nuove versioni delle chiavi. Puoi anche creare una chiave con un'ora di rotazione successiva specificata.

Console

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

Per specificare un periodo di rotazione e un'ora di inizio diversi, quando crei la chiave, ma prima di fare clic sul pulsante Crea:

  1. Fai clic sul campo Periodo di rotazione e seleziona un valore per il periodo di rotazione.

  2. Fai clic sulla data nel campo A partire dal giorno, poi seleziona una data per la rotazione successiva.

gcloud CLI

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 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 posizione di Cloud KMS del keyring.
  • ROTATION_PERIOD: l'intervallo per ruotare la chiave, ad esempio 30d per ruotarla ogni 30 giorni. Il periodo di rotazione deve essere di almeno 1 giorno e non più di 100 anni. Per ulteriori informazioni, consulta la pagina CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: il timestamp in cui 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 del comando. Per ulteriori informazioni, consulta la pagina CryptoKey.nextRotationTime.

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;
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 installare 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: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	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.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, consulta prima l'articolo sull'utilizzo di PHP su Google Cloud e installa l'SDK PHP Cloud KMS.

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\Cloud\Kms\V1\KeyManagementServiceClient;
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'
) {
    // 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.
    $createdKey = $client->createCryptoKey($keyRingName, $id, $key);
    printf('Created key with rotation: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

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

def create_key_rotation_schedule(project_id, location_id, key_ring_id, key_id):
    """
    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.

    """

    # Import the client library.
    from google.cloud import kms

    # Import time for getting the current time.
    import time

    # 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('Created labeled key: {}'.format(created_key.name))
    return created_key

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"
# 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'utilizzo dell'API. Per maggiori informazioni sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

Per creare una chiave, utilizza il metodo CryptoKey.create:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_NAME/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: lo scopo della chiave.
  • ROTATION_PERIOD: l'intervallo per ruotare la chiave, ad esempio 30d per ruotarla ogni 30 giorni. Il periodo di rotazione deve essere di almeno 1 giorno e non più di 100 anni. Per ulteriori informazioni, consulta la pagina CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: il timestamp in cui 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 del comando. Per ulteriori informazioni, consulta la pagina CryptoKey.nextRotationTime.

Imposta la durata dello stato Pianificata per l'eliminazione.

Per impostazione predefinita, le versioni delle chiavi in Cloud KMS passano 24 ore in stato Pianificata per l'eliminazione (a volte chiamata stato di eliminazione temporanea) prima di essere eliminate. La durata per la quale rimane in questo stato è configurabile, con le seguenti avvertenze:

  • La durata è configurabile solo durante la creazione della chiave.
  • Una volta specificata, la durata della chiave non può essere modificata.
  • La durata si applica a tutte le versioni della chiave create in futuro.
  • La durata minima è di 24 ore per tutte le chiavi, ad eccezione delle chiavi di sola importazione che hanno una durata minima di 0.
  • La durata massima è 120 giorni.
  • La durata predefinita è 24 ore.

Per creare una chiave che utilizza una durata personalizzata per lo stato Pianificata per l'eliminazione, procedi come segue:

Console

  1. Vai alla pagina Gestione chiavi in Google Cloud Console.

    Vai alla pagina Gestione delle chiavi

  2. Fai clic sul nome del keyring per cui vuoi creare una chiave.

  3. Fai clic su Crea chiave.

  4. Configura le impostazioni della chiave per la tua applicazione.

  5. Fai clic su Impostazioni facoltative.

  6. In Durata dello stato "pianificata per l'eliminazione", scegli per quanti giorni la chiave rimarrà pianificata per l'eliminazione prima che venga eliminata definitivamente.

  7. Fai clic su Crea chiave.

gcloud CLI

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 create key \
    --keyring key-ring \
    --location location \
    --purpose purpose \
    --destroy-scheduled-duration duration

Sostituisci key con il nome della chiave. Sostituisci key-ring con il nome del keyring in cui si troverà la chiave. Sostituisci location con la posizione di Cloud KMS del keyring. Sostituisci purpose con lo scopo della chiave, ad esempio "crittografia". Sostituisci duration con il periodo di tempo in cui la chiave rimarrà pianificata per l'eliminazione prima che venga eliminata definitivamente.

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

Ti consigliamo di utilizzare la durata predefinita di 24 ore per tutte le chiavi, a meno che tu non abbia requisiti normativi o di applicazione specifici che richiedono un valore diverso.

Crea manualmente nuove versioni della chiave

Oltre alla rotazione automatica, puoi ruotare manualmente le chiavi. Per ulteriori dettagli, consulta la sezione Chiavi di rotazione.