Crea una chiave

Questa pagina mostra come creare una chiave in Cloud KMS. Una chiave può essere una chiave di crittografia simmetrica o asimmetrica, una chiave di firma asimmetrica o una chiave di firma MAC.

Quando crei una chiave, la aggiungi a un keyring in una posizione Cloud KMS specifica. Puoi creare un nuovo portachiavi o utilizzarne uno esistente. In questa pagina, genera una nuova chiave Cloud KMS o Cloud HSM e aggiungila a un keyring esistente. Per creare una chiave Cloud EKM, consulta Crea una chiave esterna. Per importare una chiave Cloud KMS o Cloud HSM, consulta Importare una chiave.

Prima di iniziare

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

  1. Una risorsa di progetto per contenere le risorse di Cloud KMS. Google Cloud Ti consigliamo di utilizzare un progetto separato per le risorse Cloud KMS che non contenga altre risorse Google Cloud .
  2. Il nome e la posizione del keyring in cui vuoi creare la chiave. Scegli un portachiavi in una posizione vicina alle altre risorse e che supporti il livello di protezione che hai scelto. Per visualizzare le località disponibili e i livelli di protezione che supportano, consulta Località Cloud KMS. Per creare un keyring, vedi Creare un keyring.
  3. (Facoltativo) Per utilizzare gcloud CLI, prepara l'ambiente.

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    Ruoli obbligatori

    Per ottenere le autorizzazioni necessarie per creare chiavi, 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 chiavi. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

    Autorizzazioni obbligatorie

    Per creare chiavi sono necessarie le seguenti autorizzazioni:

    • cloudkms.cryptoKeys.create
    • cloudkms.cryptoKeys.get
    • cloudkms.cryptoKeys.list
    • cloudkms.cryptoKeyVersions.create
    • cloudkms.cryptoKeyVersions.get
    • cloudkms.cryptoKeyVersions.list
    • cloudkms.keyRings.get
    • cloudkms.keyRings.list
    • cloudkms.locations.get
    • cloudkms.locations.list
    • resourcemanager.projects.get
    • Per recuperare una chiave pubblica: cloudkms.cryptoKeyVersions.viewPublicKey

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

    Creare una chiave di crittografia simmetrica

    Console

    1. Nella console Google Cloud , vai alla pagina Key Management.

      Vai a Gestione delle chiavi

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

    3. Fai clic su Crea chiave.

    4. In Nome chiave, inserisci un nome per la chiave.

    5. Per Livello di protezione, seleziona Software o HSM.

    6. Per Materiale della chiave, seleziona Chiave generata.

    7. Per Finalità, seleziona Crittografia/decrittografia simmetrica.

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

    9. Fai clic su Crea.

    gcloud

    Per utilizzare Cloud KMS dalla riga di comando, devi prima installare o eseguire l'upgrade all'ultima versione di Google Cloud CLI.

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

    Sostituisci quanto segue:

    • KEY_NAME: il nome della chiave.
    • KEY_RING: il nome delle chiavi automatizzate che contengono la chiave.
    • LOCATION: la posizione di Cloud KMS delle chiavi automatizzate.
    • PROTECTION_LEVEL: il livello di protezione da utilizzare per la chiave, ad esempio software o hsm. Puoi omettere il flag --protection-level per le chiavi software.

    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.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 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"
    )
    
    // createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
    // on Cloud KMS.
    func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-symmetric-encryption-key"
    
    	// Create the client.
    	ctx := context.Background()
    	client, err := kms.NewKeyManagementClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create kms client: %w", err)
    	}
    	defer client.Close()
    
    	// Build the request.
    	req := &kmspb.CreateCryptoKeyRequest{
    		Parent:      parent,
    		CryptoKeyId: id,
    		CryptoKey: &kmspb.CryptoKey{
    			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
    			},
    		},
    	}
    
    	// Call the API.
    	result, err := client.CreateCryptoKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create key: %w", err)
    	}
    	fmt.Fprintf(w, "Created key: %s\n", result.Name)
    	return nil
    }
    

    Java

    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.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 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 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, 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;
    
    function create_key_symmetric_encrypt_decrypt(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-symmetric-key'
    ): CryptoKey {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent key ring name.
        $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
    
        // Build the key.
        $key = (new CryptoKey())
            ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

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

    Ruby

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

    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.

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

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'
    

    Sostituisci quanto segue:

    • PROJECT_ID: l'ID del progetto che contiene il portachiavi.
    • LOCATION: la posizione di Cloud KMS delle chiavi automatizzate.
    • KEY_RING: il nome delle chiavi automatizzate che contengono la chiave.
    • KEY_NAME: il nome della chiave.
    • PROTECTION_LEVEL: il livello di protezione della chiave, ad esempio SOFTWARE o HSM.
    • ALGORITHM: l'algoritmo di firma HMAC, ad esempio HMAC_SHA256. Per visualizzare tutti gli algoritmi HMAC supportati, consulta