Creazione di chiavi automatizzate

Questa pagina mostra come creare un keyring in Cloud KMS. Un keyring è la risorsa principale per le chiavi e le versioni delle chiavi Cloud KMS. Ogni keyring esiste all'interno di una determinata posizione. Per ulteriori informazioni sulle risorse Cloud KMS, consulta Risorse Cloud KMS.

Prima di iniziare

Prima di completare le attività in questa pagina, devi disporre di quanto segue:

  • Una risorsa di progetto Google Cloud per contenere le risorse Cloud KMS. Questo progetto è chiamato progetto chiave. Ti consigliamo di non includere altre risorseGoogle Cloud nel progetto chiave. Abilita l'API Cloud KMS nel progetto chiave.

    Abilitare l'API

  • Il nome della località in cui vuoi creare il keyring. Scegli una posizione vicina alle altre risorse e che supporti il livello di protezione scelto. Per visualizzare le località disponibili e i livelli di protezione supportati, consulta Località Cloud KMS.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per creare portachiavi, chiedi all'amministratore di concederti il ruolo IAM Amministratore Cloud KMS (roles/cloudkms.admin) nel progetto o in una risorsa padre. Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Questo ruolo predefinito contiene le autorizzazioni necessarie per creare portachiavi. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per creare portachiavi sono necessarie le seguenti autorizzazioni:

  • cloudkms.keyRings.create
  • cloudkms.keyRings.get
  • cloudkms.keyRings.list
  • cloudkms.locations.get
  • cloudkms.locations.list
  • resourcemanager.projects.get

Potresti anche ottenere queste autorizzazioni con ruoli personalizzati o altri ruoli predefiniti.

Creazione di chiavi automatizzate

Per creare un keyring per la nuova chiave: Se vuoi utilizzare un portachiavi esistente, puoi creare una chiave.

Console

  1. Vai alla pagina Key Management nella console Google Cloud .

    Vai a Gestione delle chiavi

  2. Fai clic su Crea keyring.

  3. In Nome della chiave automatizzata, inserisci un nome per la chiave automatizzata.

  4. Per Posizione del keyring, seleziona una posizione come "us-east1".

  5. Fai clic su Crea.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

  2. Nel tuo ambiente, esegui il comando gcloud kms keyrings create:

    gcloud kms keyrings create KEY_RING \
        --location LOCATION
    

    Sostituisci quanto segue:

    • KEY_RING: il nome delle chiavi automatizzate che contengono la chiave.
    • LOCATION: la posizione di Cloud KMS delle chiavi automatizzate.

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

C#

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo C# e installare l'SDK C# 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 innanzitutto 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"
)

// 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: %w", 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: %w", err)
	}
	fmt.Fprintf(w, "Created key ring: %s\n", result.Name)
	return nil
}

Java

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Java e installare l'SDK Java 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 innanzitutto 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, 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\CreateKeyRingRequest;
use Google\Cloud\Kms\V1\KeyRing;

function create_key_ring(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $id = 'my-key-ring'
): KeyRing {
    // 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.
    $createKeyRingRequest = (new CreateKeyRingRequest())
        ->setParent($locationName)
        ->setKeyRingId($id)
        ->setKeyRing($keyRing);
    $createdKeyRing = $client->createKeyRing($createKeyRingRequest);
    printf('Created key ring: %s' . PHP_EOL, $createdKeyRing->getName());

    return $createdKeyRing;
}

Python

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

from google.cloud import kms


def create_key_ring(
    project_id: str, location_id: str, key_ring_id: str
) -> kms.CryptoKey:
    """
    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.

    """

    # 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(f"Created key ring: {created_key_ring.name}")
    return created_key_ring

Ruby

Per eseguire questo codice, devi innanzitutto 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

Questi esempi utilizzano curl come client HTTP per dimostrare l'utilizzo dell'API. Per saperne di più sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

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

Sostituisci quanto segue:

  • PROJECT_ID: l'ID del progetto che contiene il portachiavi.
  • KEY_RING: il nome delle chiavi automatizzate che contengono la chiave.
  • LOCATION: la posizione di Cloud KMS delle chiavi automatizzate.

Per saperne di più, consulta la documentazione dell'API KeyRing.create.

Passaggi successivi