Crear clave

En esta página se explica cómo crear una clave en Cloud KMS. Una clave puede ser una clave de cifrado simétrica o asimétrica, una clave de firma asimétrica o una clave de firma MAC.

Cuando creas una clave, la añades a un conjunto de claves en una ubicación de Cloud KMS específica. Puedes crear un nuevo llavero o usar uno que ya tengas. En esta página, se genera una clave de Cloud KMS o Cloud HSM y se añade a un conjunto de claves. Para crear una clave de Cloud EKM, consulta Crear una clave externa. Para importar una clave de Cloud KMS o Cloud HSM, consulta Importar una clave.

Antes de empezar

Antes de completar las tareas de esta página, necesitas lo siguiente:

  1. Un recurso de proyecto que contenga tus recursos de Cloud KMS. Google Cloud Te recomendamos que uses un proyecto independiente para tus recursos de Cloud KMS que no contenga ningún otro recurso. Google Cloud
  2. El nombre y la ubicación del conjunto de claves en el que quieras crear la clave. Elige un llavero en una ubicación cercana a tus otros recursos y que admita el nivel de protección que hayas elegido. Para ver las ubicaciones disponibles y los niveles de protección que admiten, consulta Ubicaciones de Cloud KMS. Para crear un conjunto de claves, consulta Crear un conjunto de claves.
  3. Opcional: Para usar la CLI de gcloud, prepara tu entorno.

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    Roles obligatorios

    Para obtener los permisos que necesitas para crear claves, pide a tu administrador que te conceda el rol de gestión de identidades y accesos Administrador de Cloud KMS (roles/cloudkms.admin) en el proyecto o en un recurso principal. Para obtener más información sobre cómo conceder roles, consulta el artículo Gestionar el acceso a proyectos, carpetas y organizaciones.

    Este rol predefinido contiene los permisos necesarios para crear claves. Para ver los permisos exactos que se necesitan, despliega la sección Permisos necesarios:

    Permisos obligatorios

    Para crear claves, se necesitan los siguientes permisos:

    • 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
    • Para obtener una clave pública, sigue estos pasos: cloudkms.cryptoKeyVersions.viewPublicKey

    También puedes obtener estos permisos con roles personalizados u otros roles predefinidos.

    Crear una clave de cifrado simétrica

    Consola

    1. En la consola de Google Cloud , ve a la página Gestión de claves.

      Ir a Administración de claves

    2. Haga clic en el nombre del conjunto de claves para el que creará una clave.

    3. Haz clic en Crear clave.

    4. En Key name (Nombre de la clave), escribe el nombre de la clave.

    5. En Nivel de protección, selecciona Software o HSM.

    6. En Material de la clave, selecciona Clave generada.

    7. En Propósito, selecciona Encriptado y desencriptado simétrico.

    8. Acepta los valores predeterminados de Periodo de rotación y Empezar el.

    9. Haz clic en Crear.

    gcloud

    Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de la CLI de Google Cloud.

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

    Haz los cambios siguientes:

    • KEY_NAME: el nombre de la clave.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • PROTECTION_LEVEL: el nivel de protección que se va a usar para la clave (por ejemplo, software o hsm). Puedes omitir la marca --protection-level en las claves software.

    Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

    C#

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de C# e instalar el SDK de Cloud KMS para C#.

    
    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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de 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

    Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Ruby e instalar el SDK de Ruby de 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

    En estos ejemplos se usa curl como cliente HTTP para mostrar cómo se usa la API. Para obtener más información sobre el control de acceso, consulta el artículo sobre cómo acceder a la API Cloud KMS.

    Para crear una clave, usa el método 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" }}'
    

    Haz los cambios siguientes:

    • PROJECT_ID: el ID del proyecto que contiene el conjunto de claves.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • KEY_NAME: el nombre de la clave.
    • PROTECTION_LEVEL: el nivel de protección de la clave (por ejemplo, SOFTWARE o HSM).
    • ALGORITHM: el algoritmo de firma HMAC. Por ejemplo, HMAC_SHA256. Para ver todos los algoritmos HMAC admitidos, consulta Algoritmos de firma HMAC.

    Crear una clave de cifrado simétrica con rotación automática personalizada

    Cuando creas una clave, puedes especificar su periodo de rotación, que es el tiempo que transcurre entre la creación automática de nuevas versiones de la clave. También puedes especificar de forma independiente la próxima hora de rotación para que se produzca antes o después de un periodo de rotación a partir de ahora.

    Consola

    Cuando usas la Google Cloud consola para crear una clave, Cloud KMS define automáticamente el periodo de rotación y la próxima hora de rotación. Puede usar los valores predeterminados o especificar otros.

    Para especificar un periodo de rotación y una hora de inicio diferentes, cuando crees tu clave, pero antes de hacer clic en el botón Crear, sigue estos pasos:

    1. En Periodo de rotación de claves, selecciona una opción.

    2. En A partir del, selecciona la fecha en la que quieras que se produzca la primera rotación automática. Puedes dejar Empezar el con su valor predeterminado para iniciar la primera rotación automática un periodo de rotación de claves después de crear la clave.

    gcloud

    Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de la CLI de Google Cloud.

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

    Haz los cambios siguientes:

    • KEY_NAME: el nombre de la clave.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • ROTATION_PERIOD: el intervalo para rotar la clave. Por ejemplo, 30d para rotar la clave cada 30 días. El periodo de rotación debe ser de al menos 1 día y de 100 años como máximo. Para obtener más información, consulta CryptoKey.rotationPeriod.
    • NEXT_ROTATION_TIME: la marca de tiempo en la que se debe completar la primera rotación. Por ejemplo, 2023-01-01T01:02:03. Puedes omitir --next-rotation-time para programar la primera rotación para un periodo de rotación a partir de cuando ejecutes el comando. Para obtener más información, consulta CryptoKey.nextRotationTime.

    Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

    C#

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de C# e instalar el SDK de Cloud KMS para 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Cloud KMS.

    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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de 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

    Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Ruby e instalar el SDK de Ruby de 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

    En estos ejemplos se usa curl como cliente HTTP para mostrar cómo se usa la API. Para obtener más información sobre el control de acceso, consulta el artículo sobre cómo acceder a la API Cloud KMS.

    Para crear una clave, usa el método 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"}'
    

    Haz los cambios siguientes:

    • PURPOSE: el propósito de la clave.
    • ROTATION_PERIOD: el intervalo para rotar la clave. Por ejemplo, 30d para rotar la clave cada 30 días. El periodo de rotación debe ser de al menos 1 día y de 100 años como máximo. Para obtener más información, consulta CryptoKey.rotationPeriod.
    • NEXT_ROTATION_TIME: la marca de tiempo en la que se debe completar la primera rotación. Por ejemplo, 2023-01-01T01:02:03. Para obtener más información, consulta CryptoKey.nextRotationTime.

    Definir la duración del estado "Eliminación programada"

    De forma predeterminada, las versiones de las claves de Cloud KMS permanecen 30 días en el estado Programada para la destrucción (DESTROY_SCHEDULED) antes de destruirse. El estado de programación para la destrucción a veces se denomina estado de eliminación lógica. La duración durante la que las versiones de la clave permanecen en este estado se puede configurar, con las siguientes restricciones:

    • Solo puedes definir la duración al crear la clave.
    • Una vez que se haya especificado la duración de la clave, no se podrá cambiar.
    • La duración se aplica a todas las versiones de la clave que se creen en el futuro.
    • La duración mínima es de 24 horas para todas las claves, excepto para las claves de solo importación, que tienen una duración mínima de 0.
    • La duración máxima es de 120 días.
    • La duración predeterminada es de 30 días.

    Es posible que tu organización tenga un valor mínimo de duración programada para la destrucción definido por las políticas de la organización. Para obtener más información, consulta Control key destruction (Destrucción de claves de control).

    Para crear una clave que use una duración personalizada para el estado Programada para destrucción, sigue estos pasos:

    Consola

    1. En la consola de Google Cloud , ve a la página Gestión de claves.

      Ir a Administración de claves

    2. Haga clic en el nombre del conjunto de claves para el que creará una clave.

    3. Haz clic en Crear clave.

    4. Configura los ajustes de la clave de tu aplicación.

    5. Haz clic en Configuración adicional.

    6. En Duración del estado "programado para destrucción", elige el número de días que la clave permanecerá en el estado programado para destrucción antes de destruirse definitivamente.

    7. Haz clic en Crear clave.

    gcloud

    Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de la CLI de Google Cloud.

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose PURPOSE \
        --destroy-scheduled-duration DURATION
    

    Haz los cambios siguientes:

    • KEY_NAME: el nombre de la clave.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • PURPOSE: el propósito de la clave; por ejemplo, encryption.
    • DURATION: el tiempo que la clave permanece en el estado programada para la eliminación antes de eliminarse de forma permanente.

    Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

    Te recomendamos que uses la duración predeterminada de 30 días para todas las claves, a menos que tengas requisitos específicos de la aplicación o normativos que exijan un valor diferente.

    Crear una clave asimétrica

    En las siguientes secciones se explica cómo crear claves asimétricas.

    Crear una clave de desencriptado asimétrica

    Sigue estos pasos para crear una clave de desencriptado asimétrica en el conjunto de claves y la ubicación especificados. Estos ejemplos se pueden adaptar para especificar otro nivel de protección u otro algoritmo. Para obtener más información y valores alternativos, consulta Algoritmos y Niveles de protección.

    Cuando creas la clave por primera vez, la versión inicial tiene el estado Generación pendiente. Cuando el estado cambie a Habilitado, podrás usar la llave. Para obtener más información sobre los estados de las versiones de clave, consulte Estados de las versiones de clave.

    Consola

    1. En la consola de Google Cloud , ve a la página Gestión de claves.

      Ir a Administración de claves

    2. Haga clic en el nombre del conjunto de claves para el que creará una clave.

    3. Haz clic en Crear clave.

    4. En Key name (Nombre de la clave), escribe el nombre de la clave.

    5. En Nivel de protección, selecciona Software o HSM.

    6. En Material de la clave, selecciona Clave generada.

    7. En Propósito, selecciona Desencriptado asimétrico.

    8. En Algorithm (Algoritmo), selecciona 3072 bit RSA - OAEP Padding - SHA256 Digest (RSA de 3072 bits - Relleno OAEP - Digestión SHA256). Puedes cambiar este valor en versiones futuras de la clave.

    9. Haz clic en Crear.

    gcloud

    Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de la CLI de Google Cloud.

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "asymmetric-encryption" \
        --default-algorithm "ALGORITHM"
    

    Haz los cambios siguientes:

    • KEY_NAME: el nombre de la clave.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • ALGORITHM: el algoritmo que se va a usar para la clave. Por ejemplo, rsa-decrypt-oaep-3072-sha256. Para ver una lista de los algoritmos de cifrado asimétrico admitidos, consulta Algoritmos de cifrado asimétrico.

    Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

    C#

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de C# e instalar el SDK de Cloud KMS para C#.

    
    using Google.Cloud.Kms.V1;
    using Google.Protobuf.WellKnownTypes;
    
    public class CreateKeyAsymmetricDecryptSample
    {
        public CryptoKey CreateKeyAsymmetricDecrypt(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-asymmetric-encrypt-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.AsymmetricDecrypt,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaDecryptOaep2048Sha256,
                },
    
                // Optional: customize how long key versions should be kept before destroying.
                DestroyScheduledDuration = new Duration
                {
                    Seconds = 24 * 60 * 60,
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // Return the result.
            return result;
        }
    }

    Go

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Cloud KMS.

    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"
    )
    
    // createKeyAsymmetricDecrypt creates a new asymmetric RSA encrypt/decrypt key
    // pair where the private key is stored in Cloud KMS.
    func createKeyAsymmetricDecrypt(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-asymmetric-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_ASYMMETRIC_DECRYPT,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_RSA_DECRYPT_OAEP_2048_SHA256,
    			},
    
    			// Optional: customize how long key versions should be kept before destroying.
    			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
    		},
    	}
    
    	// 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de 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 java.io.IOException;
    
    public class CreateKeyAsymmetricDecrypt {
    
      public void createKeyAsymmetricDecrypt() 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-asymmetric-decryption-key";
        createKeyAsymmetricDecrypt(projectId, locationId, keyRingId, id);
      }
    
      // Create a new asymmetric key for the purpose of encrypting and decrypting
      // data.
      public void createKeyAsymmetricDecrypt(
          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 asymmetric key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.ASYMMETRIC_DECRYPT)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256))
    
                  // Optional: customize how long key versions should be kept before destroying.
                  .setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24 * 60 * 60))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created asymmetric key %s%n", createdKey.getName());
        }
      }
    }

    Node.js

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de 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-asymmetric-decrypt-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 createKeyAsymmetricDecrypt() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'ASYMMETRIC_DECRYPT',
          versionTemplate: {
            algorithm: 'RSA_DECRYPT_OAEP_2048_SHA256',
          },
    
          // Optional: customize how long key versions should be kept before
          // destroying.
          destroyScheduledDuration: {seconds: 60 * 60 * 24},
        },
      });
    
      console.log(`Created asymmetric key: ${key.name}`);
      return key;
    }
    
    return createKeyAsymmetricDecrypt();

    PHP

    Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de 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;
    
    function create_key_asymmetric_decrypt(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-asymmetric-decrypt-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::ASYMMETRIC_DECRYPT)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_DECRYPT_OAEP_2048_SHA256)
            )
    
            // Optional: customize how long key versions should be kept before destroying.
            ->setDestroyScheduledDuration((new Duration())
                ->setSeconds(24 * 60 * 60)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created asymmetric decryption key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Cloud KMS.

    import datetime
    
    # Import the client library.
    from google.cloud import kms
    from google.protobuf import duration_pb2  # type: ignore
    
    
    def create_key_asymmetric_decrypt(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new asymmetric 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-asymmetric-decrypt-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.ASYMMETRIC_DECRYPT
        algorithm = (
            kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256
        )
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
            # Optional: customize how long key versions should be kept before
            # destroying.
            "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
                datetime.timedelta(days=1)
            ),
        }
    
        # 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 asymmetric decrypt key: {created_key.name}")
        return created_key
    
    

    Ruby

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Ruby e instalar el SDK de Ruby de 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-asymmetric-decrypt-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:          :ASYMMETRIC_DECRYPT,
      version_template: {
        algorithm: :RSA_DECRYPT_OAEP_2048_SHA256
      },
    
      # Optional: customize how long key versions should be kept before destroying.
      destroy_scheduled_duration: {
        seconds: 24 * 60 * 60
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created asymmetric decryption key: #{created_key.name}"

    API

    En estos ejemplos se usa curl como cliente HTTP para mostrar cómo se usa la API. Para obtener más información sobre el control de acceso, consulta el artículo sobre cómo acceder a la API Cloud KMS.

    Crea una clave de desencriptado asimétrica llamando a 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": "ASYMMETRIC_DECRYPT", "versionTemplate": {"algorithm": "ALGORITHM"}}'
    

    Haz los cambios siguientes:

    • PROJECT_ID: el ID del proyecto que contiene el conjunto de claves.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • KEY_NAME: el nombre de la clave.
    • ALGORITHM: el algoritmo que se va a usar para la clave (por ejemplo, RSA_DECRYPT_OAEP_3072_SHA256). Para ver una lista de los algoritmos de cifrado asimétrico admitidos, consulta Algoritmos de cifrado asimétrico.

    Crear una clave de firma asimétrica

    Sigue estos pasos para crear una clave de firma asimétrica en el llavero y la ubicación especificados. Estos ejemplos se pueden adaptar para especificar otro nivel de protección u otro algoritmo. Para obtener más información y valores alternativos, consulta Algoritmos y Niveles de protección.

    Cuando creas la clave por primera vez, la versión inicial tiene el estado Generación pendiente. Cuando el estado cambie a Habilitado, podrás usar la llave. Para obtener más información sobre los estados de las versiones de clave, consulte Estados de las versiones de clave.

    Consola

    1. En la consola de Google Cloud , ve a la página Gestión de claves.

      Ir a Administración de claves

    2. Haga clic en el nombre del conjunto de claves para el que creará una clave.

    3. Haz clic en Crear clave.

    4. En Key name (Nombre de la clave), escribe el nombre de la clave.

    5. En Nivel de protección, selecciona Software o HSM.

    6. En Material de la clave, selecciona Clave generada.

    7. En Propósito, selecciona Firma asimétrica.

    8. En Algorithm (Algoritmo), selecciona Elliptic Curve P-256 - SHA256 Digest (Curva elíptica P-256 - Digest SHA256). Puedes cambiar este valor en versiones futuras de la clave.

    9. Haz clic en Crear.

    gcloud

    Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de la CLI de Google Cloud.

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "asymmetric-signing" \
        --default-algorithm "ALGORITHM"
    

    Haz los cambios siguientes:

    • KEY_NAME: el nombre de la clave.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • ALGORITHM: el algoritmo que se va a usar para la clave (por ejemplo, ec-sign-p256-sha256). Para ver una lista de los algoritmos admitidos, consulta Algoritmos de firma asimétricos.

    Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

    C#

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de C# e instalar el SDK de Cloud KMS para C#.

    
    using Google.Cloud.Kms.V1;
    using Google.Protobuf.WellKnownTypes;
    
    public class CreateKeyAsymmetricSignSample
    {
        public CryptoKey CreateKeyAsymmetricSign(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-asymmetric-signing-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.AsymmetricSign,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaSignPkcs12048Sha256,
                },
    
                // Optional: customize how long key versions should be kept before destroying.
                DestroyScheduledDuration = new Duration
                {
                    Seconds = 24 * 60 * 60,
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // Return the result.
            return result;
        }
    }

    Go

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Cloud KMS.

    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"
    )
    
    // createKeyAsymmetricSign creates a new asymmetric RSA sign/verify key pair
    // where the private key is stored in Cloud KMS.
    func createKeyAsymmetricSign(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-asymmetric-signing-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_ASYMMETRIC_SIGN,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
    			},
    
    			// Optional: customize how long key versions should be kept before destroying.
    			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
    		},
    	}
    
    	// 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de 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 java.io.IOException;
    
    public class CreateKeyAsymmetricSign {
    
      public void createKeyAsymmetricSign() 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-asymmetric-signing-key";
        createKeyAsymmetricSign(projectId, locationId, keyRingId, id);
      }
    
      // Create a new asymmetric key for the purpose of signing and verifying data.
      public void createKeyAsymmetricSign(
          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 asymmetric key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256))
    
                  // Optional: customize how long key versions should be kept before destroying.
                  .setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24 * 60 * 60))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created asymmetric key %s%n", createdKey.getName());
        }
      }
    }

    Node.js

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de 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-asymmetric-sign-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 createKeyAsymmetricSign() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'ASYMMETRIC_SIGN',
          versionTemplate: {
            algorithm: 'RSA_SIGN_PKCS1_2048_SHA256',
          },
    
          // Optional: customize how long key versions should be kept before
          // destroying.
          destroyScheduledDuration: {seconds: 60 * 60 * 24},
        },
      });
    
      console.log(`Created asymmetric key: ${key.name}`);
      return key;
    }
    
    return createKeyAsymmetricSign();

    PHP

    Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de 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;
    
    function create_key_asymmetric_sign(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-asymmetric-signing-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::ASYMMETRIC_SIGN)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_SIGN_PKCS1_2048_SHA256)
            )
    
            // Optional: customize how long key versions should be kept before destroying.
            ->setDestroyScheduledDuration((new Duration())
                ->setSeconds(24 * 60 * 60)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created asymmetric signing key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Cloud KMS.

    
    import datetime
    
    # Import the client library.
    from google.cloud import kms
    from google.protobuf import duration_pb2  # type: ignore
    
    
    def create_key_asymmetric_sign(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new asymmetric signing 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-asymmetric-signing-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.ASYMMETRIC_SIGN
        algorithm = (
            kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256
        )
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
            # Optional: customize how long key versions should be kept before
            # destroying.
            "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
                datetime.timedelta(days=1)
            ),
        }
    
        # 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 asymmetric signing key: {created_key.name}")
        return created_key
    
    

    Ruby

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Ruby e instalar el SDK de Ruby de 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-asymmetric-signing-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:          :ASYMMETRIC_SIGN,
      version_template: {
        algorithm: :RSA_SIGN_PKCS1_2048_SHA256
      },
    
      # Optional: customize how long key versions should be kept before destroying.
      destroy_scheduled_duration: {
        seconds: 24 * 60 * 60
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created asymmetric signing key: #{created_key.name}"

    API

    En estos ejemplos se usa curl como cliente HTTP para mostrar cómo se usa la API. Para obtener más información sobre el control de acceso, consulta el artículo sobre cómo acceder a la API Cloud KMS.

    Crea una clave de firma asimétrica llamando a 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": "ASYMMETRIC_SIGN", "versionTemplate": {"algorithm": "ALGORITHM"}}'
    

    Haz los cambios siguientes:

    • PROJECT_ID: el ID del proyecto que contiene el conjunto de claves.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • KEY_NAME: el nombre de la clave.
    • ALGORITHM: el algoritmo que se va a usar para la clave (por ejemplo, EC_SIGN_P256_SHA256). Para ver una lista de los algoritmos admitidos, consulta Algoritmos de firma asimétrica.

    Obtener la clave pública

    Cuando creas una clave asimétrica, Cloud KMS crea un par de claves pública y privada. Puedes recuperar la clave pública de una clave asimétrica habilitada en cualquier momento después de que se genere la clave.

    La clave pública está en formato de correo electrónico con privacidad mejorada (PEM). Para obtener más información, consulta las secciones General Considerations y Textual Encoding of Subject Public Key Info de la RFC 7468.

    Para descargar la clave pública de una versión de clave asimétrica, sigue estos pasos:

    Consola

    1. En la consola de Google Cloud , ve a la página Gestión de claves.

      Ir a Administración de claves

    2. Haga clic en el nombre del conjunto de claves que contiene la clave asimétrica de la que quiere obtener la clave pública.

    3. Haga clic en el nombre de la clave de la que quiera obtener la clave pública.

    4. En la fila correspondiente a la versión de la clave de la que quieras obtener la clave pública, haz clic en Ver más .

    5. Haz clic en Descargar clave pública.

    6. La clave pública se muestra en la petición. Puedes copiar la clave pública en el portapapeles. Para descargar la clave pública, haga clic en Descargar.

    Si no ves la opción Obtener clave pública, comprueba lo siguiente:

    • La clave es una clave asimétrica.
    • La versión de la clave está habilitada.
    • Tienes el permiso cloudkms.cryptoKeyVersions.viewPublicKey.

    El nombre de archivo de una clave pública descargada de la consola Google Cloud tiene el siguiente formato:

    KEY_RING-KEY_NAME-KEY_VERSION.pub
    

    Cada parte del nombre de archivo está separada por un guion. Por ejemplo: ringname-keyname-version.pub

    gcloud

    Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de la CLI de Google Cloud.

    gcloud kms keys versions get-public-key KEY_VERSION \
        --key KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --public-key-format PUBLIC_KEY_FORMAT \
        --output-file OUTPUT_FILE_PATH
    

    Haz los cambios siguientes:

    • KEY_VERSION: número de versión de la clave.
    • KEY_NAME: el nombre de la clave.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • PUBLIC_KEY_FORMAT: el formato en el que quieres exportar la clave pública. Para los algoritmos PQC (vista previa), usa nist-pqc. Para todas las demás claves, puede usar pem u omitir este parámetro.
    • OUTPUT_FILE_PATH: la ruta en la que quieres guardar el archivo de clave pública. Por ejemplo, public-key.pub.

    Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

    C#

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de C# e instalar el SDK de Cloud KMS para C#.

    
    using Google.Cloud.Kms.V1;
    
    public class GetPublicKeySample
    {
        public PublicKey GetPublicKey(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.
            PublicKey result = client.GetPublicKey(keyVersionName);
    
            // Return the ciphertext.
            return result;
        }
    }

    Go

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Cloud KMS.

    import (
    	"context"
    	"crypto/x509"
    	"encoding/pem"
    	"fmt"
    	"hash/crc32"
    	"io"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    )
    
    // getPublicKey retrieves the public key from an asymmetric key pair on
    // Cloud KMS.
    func getPublicKey(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.GetPublicKeyRequest{
    		Name: name,
    	}
    
    	// Call the API.
    	result, err := client.GetPublicKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get public key: %w", err)
    	}
    
    	// The 'Pem' field is the raw string representation of the public key.
    	// Convert 'Pem' into bytes for further processing.
    	key := []byte(result.Pem)
    
    	// Optional, but recommended: perform integrity verification on result.
    	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
    	// https://cloud.google.com/kms/docs/data-integrity-guidelines
    	crc32c := func(data []byte) uint32 {
    		t := crc32.MakeTable(crc32.Castagnoli)
    		return crc32.Checksum(data, t)
    	}
    	if int64(crc32c(key)) != result.PemCrc32C.Value {
    		return fmt.Errorf("getPublicKey: response corrupted in-transit")
    	}
    
    	// Optional - parse the public key. This transforms the string key into a Go
    	// PublicKey.
    	block, _ := pem.Decode(key)
    	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
    	if err != nil {
    		return fmt.Errorf("failed to parse public key: %w", err)
    	}
    	fmt.Fprintf(w, "Retrieved public key: %v\n", publicKey)
    	return nil
    }
    

    Java

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de Cloud KMS.

    import com.google.cloud.kms.v1.CryptoKeyVersionName;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.PublicKey;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    
    public class GetPublicKey {
    
      public void getPublicKey() throws IOException, GeneralSecurityException {
        // 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";
        getPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
      }
    
      // Get the public key associated with an asymmetric key.
      public void getPublicKey(
          String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
          throws IOException, GeneralSecurityException {
        // 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);
    
          // Get the public key.
          PublicKey publicKey = client.getPublicKey(keyVersionName);
          System.out.printf("Public key: %s%n", publicKey.getPem());
        }
      }
    }

    Node.js

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de 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 version name
    const versionName = client.cryptoKeyVersionPath(
      projectId,
      locationId,
      keyRingId,
      keyId,
      versionId
    );
    
    async function getPublicKey() {
      const [publicKey] = await client.getPublicKey({
        name: versionName,
      });
    
      // Optional, but recommended: perform integrity verification on publicKey.
      // For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
      // https://cloud.google.com/kms/docs/data-integrity-guidelines
      const crc32c = require('fast-crc32c');
      if (publicKey.name !== versionName) {
        throw new Error('GetPublicKey: request corrupted in-transit');
      }
      if (crc32c.calculate(publicKey.pem) !== Number(publicKey.pemCrc32c.value)) {
        throw new Error('GetPublicKey: response corrupted in-transit');
      }
    
      console.log(`Public key pem: ${publicKey.pem}`);
    
      return publicKey;
    }
    
    return getPublicKey();

    PHP

    Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de Cloud KMS.

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\GetPublicKeyRequest;
    
    function get_public_key(
        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.
        $getPublicKeyRequest = (new GetPublicKeyRequest())
            ->setName($keyVersionName);
        $publicKey = $client->getPublicKey($getPublicKeyRequest);
        printf('Public key: %s' . PHP_EOL, $publicKey->getPem());
    
        return $publicKey;
    }

    Python

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Cloud KMS.

    from google.cloud import kms
    
    
    def get_public_key(
        project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
    ) -> kms.PublicKey:
        """
        Get the public key for an asymmetric 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 use (e.g. '1').
    
        Returns:
            PublicKey: Cloud KMS public key response.
    
        """
    
        # 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.
        public_key = client.get_public_key(request={"name": key_version_name})
    
        # Optional, but recommended: perform integrity verification on public_key.
        # For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
        # https://cloud.google.com/kms/docs/data-integrity-guidelines
        if not public_key.name == key_version_name:
            raise Exception("The request sent to the server was corrupted in-transit.")
        # See crc32c() function defined below.
        if not public_key.pem_crc32c == crc32c(public_key.pem.encode("utf-8")):
            raise Exception(
                "The response received from the server was corrupted in-transit."
            )
        # End integrity verification
    
        print(f"Public key: {public_key.pem}")
        return public_key
    
    
    def crc32c(data: bytes) -> int:
        """
        Calculates the CRC32C checksum of the provided data.
        Args:
            data: the bytes over which the checksum should be calculated.
        Returns:
            An int representing the CRC32C checksum of the provided bytes.
        """
        import crcmod  # type: ignore
    
        crc32c_fun = crcmod.predefined.mkPredefinedCrcFun("crc-32c")
        return crc32c_fun(data)
    
    

    Ruby

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Ruby e instalar el SDK de Ruby de 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.
    public_key = client.get_public_key name: key_version_name
    puts "Public key: #{public_key.pem}"

    API

    En estos ejemplos se usa curl como cliente HTTP para mostrar cómo se usa la API. Para obtener más información sobre el control de acceso, consulta el artículo sobre cómo acceder a la API Cloud KMS.

    Recupera la clave pública llamando al método CryptoKeyVersions.getPublicKey.

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION/publicKey?public_key_format=PUBLIC_KEY_FORMAT" \
        --request "GET" \
        --header "authorization: Bearer TOKEN"
    

    Haz los cambios siguientes:

    • PROJECT_ID: el ID del proyecto que contiene el conjunto de claves.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • KEY_NAME: el nombre de la clave.
    • KEY_VERSION: número de versión de la clave.
    • PUBLIC_KEY_FORMAT: el formato en el que quieres exportar la clave pública. Para los algoritmos PQC (vista previa), usa NIST_PQC. Para todas las demás claves, puede usar PEM u omitir este parámetro.

    Si se omite el formato de clave pública de una clave no PQC, el resultado será similar al siguiente:

    {
      "pem": "-----BEGIN PUBLIC KEY-----\nQ29uZ3JhdHVsYXRpb25zLCB5b3UndmUgZGlzY292ZX
              JlZCB0aGF0IHRoaXMgaXNuJ3QgYWN0dWFsbHkgYSBwdWJsaWMga2V5ISBIYXZlIGEgbmlj
              ZSBkYXkgOik=\n-----END PUBLIC KEY-----\n",
      "algorithm": "ALGORITHM",
      "pemCrc32c": "2561089887",
      "name": "projects/PROJECT_ID/locations/LOCATION/keyRings/
               KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/
               KEY_VERSION",
      "protectionLevel": "PROTECTION_LEVEL"
    }

    En el caso de un algoritmo PQC con formato de clave pública NIST_PQC, el resultado es similar al siguiente:

    {
      "publicKeyFormat": "NIST_PQC",
      "publicKey": {
        "crc32cChecksum": "1985843562",
        "data": "kdcOIrFCC5kN8S4i0+R+AoSc9gYIJ9jEQ6zG235ZmCQ="
      }
      "algorithm": "ALGORITHM",
      "name": "projects/PROJECT_ID/locations/LOCATION/keyRings/
               KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/
               KEY_VERSION",
      "protectionLevel": "PROTECTION_LEVEL"
    }

    Convertir una clave pública al formato JWK

    Cloud KMS te permite obtener una clave pública en formato PEM. Es posible que algunas aplicaciones requieran otros formatos de clave, como JSON Web Key (JWK). Para obtener más información sobre el formato JWK, consulta el estándar RFC 7517.

    Para convertir una clave pública al formato JWK, sigue estos pasos:

    Go

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Cloud KMS.

    import (
    	"context"
    	"crypto/x509"
    	"encoding/json"
    	"encoding/pem"
    	"fmt"
    	"hash/crc32"
    	"io"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    	"github.com/lestrrat-go/jwx/v2/jwk"
    )
    
    // getPublicKeyJwk retrieves the public key from an asymmetric key pair on Cloud KMS.
    func getPublicKeyJwk(w io.Writer, cryptoKeyVersionName 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.GetPublicKeyRequest{
    		Name: cryptoKeyVersionName,
    	}
    
    	// Call the API to get the public key.
    	result, err := client.GetPublicKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get public key: %w", err)
    	}
    
    	// The 'Pem' field is the raw string representation of the public key.
    	// Convert 'Pem' into bytes for further processing.
    	key := []byte(result.Pem)
    
    	// Optional, but recommended: perform integrity verification on result.
    	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
    	// https://cloud.google.com/kms/docs/data-integrity-guidelines
    	crc32c := func(data []byte) uint32 {
    		t := crc32.MakeTable(crc32.Castagnoli)
    		return crc32.Checksum(data, t)
    	}
    	if int64(crc32c(key)) != result.PemCrc32C.Value {
    		return fmt.Errorf("getPublicKey: response corrupted in-transit")
    	}
    
    	// Optional - parse the public key.
    	// This transforms the string key into a Go PublicKey.
    	block, _ := pem.Decode(key)
    	_, err = x509.ParsePKIXPublicKey(block.Bytes)
    	if err != nil {
    		return fmt.Errorf("failed to parse public key: %w", err)
    	}
    
    	// If all above checks pass, convert it into JWK format.
    	jwkKey, err := jwk.ParseKey(key, jwk.WithPEM(true))
    	if err != nil {
    		return fmt.Errorf("Failed to parse the PEM public key: %w", err)
    	}
    
    	fmt.Fprintf(w, "The public key in JWK format: ")
    	json.NewEncoder(w).Encode(jwkKey)
    	return nil
    }
    

    Java

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de Cloud KMS.

    import com.google.cloud.kms.v1.CryptoKeyVersionName;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.PublicKey;
    // NOTE: The library nimbusds is NOT endorsed for anything beyond conversion to JWK.
    import com.nimbusds.jose.JOSEException;
    import com.nimbusds.jose.jwk.JWK;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    
    public class ConvertPublicKeyToJwk {
    
      public void convertPublicKey() throws IOException, GeneralSecurityException, JOSEException {
        // 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";
        convertPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
      }
    
      // (Get and) Convert the public key associated with an asymmetric key.
      public void convertPublicKey(
          String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
          throws IOException, GeneralSecurityException, JOSEException {
        // 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);
    
          // Get the public key and convert it to JWK format.
          PublicKey publicKey = client.getPublicKey(keyVersionName);
          JWK jwk = JWK.parseFromPEMEncodedObjects(publicKey.getPem());
          System.out.println(jwk.toJSONString());
        }
      }
    }

    Python

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Cloud KMS.

    from google.cloud import kms
    from jwcrypto import jwk
    
    
    def get_public_key_jwk(
        project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
    ) -> kms.PublicKey:
        """
        Get the public key of an asymmetric key in JWK format.
    
        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 use (e.g. '1').
    
        Returns:
            PublicKey: Cloud KMS public key response.
    
        """
    
        # 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.
        public_key = client.get_public_key(request={"name": key_version_name})
    
        # Optional, but recommended: perform integrity verification on public_key.
        # For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
        # https://cloud.google.com/kms/docs/data-integrity-guidelines
        if not public_key.name == key_version_name:
            raise Exception("The request sent to the server was corrupted in-transit.")
        # See crc32c() function defined below.
        if not public_key.pem_crc32c == crc32c(public_key.pem.encode("utf-8")):
            raise Exception(
                "The response received from the server was corrupted in-transit."
            )
        # End integrity verification
    
        # Convert to JWK format.
        jwk_key = jwk.JWK.from_pem(public_key.pem.encode())
        return jwk_key.export(private_key=False)
    
    
    def crc32c(data: bytes) -> int:
        """
        Calculates the CRC32C checksum of the provided data.
        Args:
            data: the bytes over which the checksum should be calculated.
        Returns:
            An int representing the CRC32C checksum of the provided bytes.
        """
        import crcmod  # type: ignore
    
        crc32c_fun = crcmod.predefined.mkPredefinedCrcFun("crc-32c")
        return crc32c_fun(data)
    
    

    Controlar el acceso a las claves asimétricas

    Un firmante o validador requiere el permiso o el rol adecuado en la clave asimétrica.

    • Concede el permiso cloudkms.cryptoKeyVersions.useToSign a un usuario o servicio que vaya a realizar la firma en la clave asimétrica.

    • Concede el permiso cloudkms.cryptoKeyVersions.viewPublicKey a un usuario o servicio que vaya a obtener la clave pública de la clave asimétrica. La clave pública es obligatoria para validar la firma.

    Consulta información sobre los permisos y los roles de la versión de Cloud KMS en Permisos y roles.

    Crear una clave de firma MAC

    Consola

    1. En la consola de Google Cloud , ve a la página Gestión de claves.

      Ir a Administración de claves

    2. Haga clic en el nombre del conjunto de claves para el que creará una clave.

    3. Haz clic en Crear clave.

    4. En Key name (Nombre de la clave), escribe el nombre de la clave.

    5. En Nivel de protección, selecciona Software o HSM.

    6. En Material de la clave, selecciona Clave generada.

    7. En Propósito, selecciona Firma o verificación de MAC.

    8. Opcional: en Algoritmo, selecciona un algoritmo de firma HMAC.

    9. Haz clic en Crear.

    gcloud

    Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de la CLI de Google Cloud.

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "mac" \
        --default-algorithm "ALGORITHM" \
        --protection-level "PROTECTION_LEVEL"
    

    Haz los cambios siguientes:

    • KEY_NAME: el nombre de la clave.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • ALGORITHM: el algoritmo de firma HMAC. Por ejemplo, hmac-sha256. Para ver todos los algoritmos HMAC admitidos, consulta Algoritmos de firma HMAC.
    • PROTECTION_LEVEL: el nivel de protección de la clave (por ejemplo, hsm). Puedes omitir la marca --protection-level en las claves software .

    Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

    C#

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de C# e instalar el SDK de Cloud KMS para C#.

    
    using Google.Cloud.Kms.V1;
    using Google.Protobuf.WellKnownTypes;
    
    public class CreateKeyMacSample
    {
        public CryptoKey CreateKeyMac(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-mac-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.Mac,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.HmacSha256,
                },
    
                // Optional: customize how long key versions should be kept before destroying.
                DestroyScheduledDuration = new Duration
                {
                    Seconds = 24 * 60 * 60,
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // Return the result.
            return result;
        }
    }

    Go

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Cloud KMS.

    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"
    )
    
    // createKeyMac creates a new key for use with MacSign.
    func createKeyMac(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-mac-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_MAC,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_HMAC_SHA256,
    			},
    
    			// Optional: customize how long key versions should be kept before destroying.
    			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
    		},
    	}
    
    	// 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

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de 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 CreateKeyMac {
    
      public void createKeyMac() 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-mac-key";
        createKeyMac(projectId, locationId, keyRingId, id);
      }
    
      // Create a new key for use with MacSign.
      public void createKeyMac(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 mac key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.MAC)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.HMAC_SHA256))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created mac key %s%n", createdKey.getName());
        }
      }
    }

    Node.js

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de 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-mac-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 createKeyMac() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'MAC',
          versionTemplate: {
            algorithm: 'HMAC_SHA256',
          },
    
          // Optional: customize how long key versions should be kept before
          // destroying.
          destroyScheduledDuration: {seconds: 60 * 60 * 24},
        },
      });
    
      console.log(`Created mac key: ${key.name}`);
      return key;
    }
    
    return createKeyMac();

    PHP

    Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de 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;
    
    function create_key_mac(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-mac-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::MAC)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::HMAC_SHA256)
            )
    
            // Optional: customize how long key versions should be kept before destroying.
            ->setDestroyScheduledDuration((new Duration())
                ->setSeconds(24 * 60 * 60)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created mac key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Cloud KMS.

    
    import datetime
    
    from google.cloud import kms
    from google.protobuf import duration_pb2  # type: ignore
    
    
    def create_key_mac(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new key in Cloud KMS for HMAC operations.
    
        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-mac-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.MAC
        algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.HMAC_SHA256
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
            # Optional: customize how long key versions should be kept before
            # destroying.
            "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
                datetime.timedelta(days=1)
            ),
        }
    
        # 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 mac key: {created_key.name}")
        return created_key
    
    

    Ruby

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Ruby e instalar el SDK de Ruby de 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-mac-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:          :MAC,
      version_template: {
        algorithm: :HMAC_SHA256
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created mac key: #{created_key.name}"

    API

    En estos ejemplos se usa curl como cliente HTTP para mostrar cómo se usa la API. Para obtener más información sobre el control de acceso, consulta el artículo sobre cómo acceder a la API Cloud KMS.

    Para crear una clave, usa el método 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": "MAC", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'
    

    Haz los cambios siguientes:

    • PROJECT_ID: el ID del proyecto que contiene el conjunto de claves.
    • LOCATION: la ubicación de Cloud KMS del conjunto de claves.
    • KEY_RING: el nombre del conjunto de claves que contiene la clave.
    • KEY_NAME: el nombre de la clave.
    • PROTECTION_LEVEL: el nivel de protección de la llave (por ejemplo, SOFTWARE o HSM).
    • ALGORITHM: el algoritmo de firma HMAC, por ejemplo, HMAC_SHA256. Para ver todos los algoritmos HMAC admitidos, consulta Algoritmos de firma HMAC.

    Siguientes pasos