Crear una clave

En esta página, se muestra cómo crear una clave en Cloud KMS. Puede ser una clave de criptografía simétrica o asimétrica, una clave de firma asimétrica o una clave de firma MAC.

Cuando creas una clave, la agregas a un llavero de claves en una ubicación de Cloud KMS específica. Puedes crear un llavero de claves nuevo o usar uno existente. En esta página, generarás una clave nueva de Cloud KMS o Cloud HSM y la agregarás a un llavero de claves existente. Para crear una clave de Cloud EKM, consulta Crea una clave externa. Para importar una clave de Cloud KMS o de Cloud HSM, consulta Importa una clave.

Antes de comenzar

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

  • Un recurso de proyecto de Google Cloud que contenga tus recursos de Cloud KMS. Te recomendamos usar un proyecto separado para tus recursos de Cloud KMS que no contenga ningún otro recurso de Google Cloud.
  • El nombre y la ubicación del llavero de claves en el que quieres crear tu clave. Elige un llavero de claves en una ubicación cercana a tus otros recursos y que admita el nivel de protección deseado. Para ver las ubicaciones disponibles y los niveles de protección que admiten, consulta las ubicaciones de Cloud KMS. Para crear un llavero de claves, consulta Crea un llavero de claves.
  • Opcional: Para usar gcloud CLI, prepara tu entorno.

    gcloud CLI

    En la consola de Google Cloud, activa Cloud Shell.

    Activar Cloud Shell

Funciones obligatorias

Si quieres obtener los permisos que necesitas para crear claves, pídele a tu administrador que te otorgue el rol de IAM Administrador de Cloud KMS (roles/cloudkms.admin) en el proyecto o en un recurso superior. Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso.

Este rol predefinido contiene los permisos necesarios para crear claves. Para ver los permisos exactos que son necesarios, expande la sección Permisos requeridos:

Permisos necesarios

Se requieren los siguientes permisos para crear claves:

  • 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 recuperar una clave pública: cloudkms.cryptoKeyVersions.viewPublicKey

Es posible que también puedas obtener estos permisos con funciones personalizadas o con otras funciones predefinidas.

Crea una clave de encriptación simétrica

Console

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

    Ir a Key Management

  2. Haz clic en el nombre del llavero de claves para el que crearás la clave.

  3. Haz clic en Crear clave.

  4. En Nombre de la clave, ingresa un nombre.

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

  6. En Material de clave, selecciona Clave generada.

  7. En Propósito, selecciona Encriptación/desencriptación simétrica.

  8. Acepta los valores predeterminados de Período de rotación y A partir del.

  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 Google Cloud CLI.

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

Reemplaza lo siguiente:

  • KEY_NAME: el nombre de la clave.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • PROTECTION_LEVEL: Es el nivel de protección que se usará para la clave, por ejemplo, software o hsm. Puedes omitir la marca --protection-level para 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 configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


using Google.Cloud.Kms.V1;

public class CreateKeySymmetricEncryptDecryptSample
{
    public CryptoKey CreateKeySymmetricEncryptDecrypt(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-symmetric-encryption-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

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

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

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

        // Return the result.
        return result;
    }
}

Go

Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para 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 configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para 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 configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para 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 obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para 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 configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para 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 configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para 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 un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de 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" }}'

Reemplaza lo siguiente:

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

Crea una clave de encriptación simétrica con rotación automática personalizada

Cuando creas una clave, puedes especificar su período de rotación, que es el tiempo que transcurre entre la creación automática de versiones de claves nuevas. También puedes especificar de forma independiente la próxima fecha de rotación para que la siguiente rotación ocurra antes o después de un período de rotación a partir de ahora.

Console

Cuando usas la consola de Google Cloud para crear una clave, Cloud KMS establece el período de rotación y la próxima fecha de rotación automáticamente. Puedes usar los valores predeterminados o especificar valores diferentes.

Para especificar un período de rotación y una hora de inicio diferentes, cuando creas la clave, pero antes de hacer clic en el botón Crear, haz lo siguiente:

  1. En Período de rotación de claves, selecciona una opción.

  2. En A partir del, selecciona la fecha en la que deseas que ocurra la primera rotación automática. Puedes dejar A partir del en su valor predeterminado para iniciar la primera rotación automática un período de rotación de claves desde el momento en que creaste 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 Google Cloud CLI.

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

Reemplaza lo siguiente:

  • KEY_NAME: el nombre de la clave.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • ROTATION_PERIOD: Es el intervalo en el que se rota la clave; por ejemplo, 30d para rotar la clave cada 30 días. El período de rotación debe ser de 1 día como mínimo y 100 años como máximo. Para obtener más información, consulta CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: Es la marca de tiempo en la que se completa la primera rotación, por ejemplo, "2023-01-01T01:02:03". Puedes omitir --next-rotation-time para programar la primera rotación durante 7 días desde que ejecutas 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 configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;
using System;

public class CreateKeyRotationScheduleSample
{
    public CryptoKey CreateKeyRotationSchedule(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-key-with-rotation-schedule")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

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

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

            // Rotate the key every 30 days.
            RotationPeriod = new Duration
            {
                Seconds = 60 * 60 * 24 * 30, // 30 days
            },

            // Start the first rotation in 24 hours.
            NextRotationTime = new Timestamp
            {
                Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
            }
        };

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

        // Return the result.
        return result;
    }
}

Go

Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para 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 configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para 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 configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para 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 obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para 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 configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para 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 configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para 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 un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de 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"}'

Reemplaza lo siguiente:

  • PURPOSE: Es el propósito de la clave.
  • ROTATION_PERIOD: Es el intervalo en el que se rota la clave; por ejemplo, 30d para rotar la clave cada 30 días. El período de rotación debe ser de 1 día como mínimo y 100 años como máximo. Para obtener más información, consulta CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: Es la marca de tiempo en la que se completa la primera rotación, por ejemplo, "2023-01-01T01:02:03". Puedes omitir --next-rotation-time para programar la primera rotación durante 7 días desde que ejecutas el comando. Para obtener más información, consulta CryptoKey.nextRotationTime.

Establece la duración del estado "Programada para destrucción"

Según la configuración predeterminada, las versiones de claves en Cloud KMS pasan 24 horas en el estado programado para destrucción (DESTROY_SCHEDULED) antes de destruirse. A veces, el estado programado para destrucción se denomina estado borrado de forma no definitiva. La duración durante la cual las versiones de claves permanecen en este estado se puede configurar, con las siguientes restricciones:

  • Solo puedes establecer la duración durante la creación de la clave.
  • Una vez que se especifica la duración de la clave, no se puede 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 las 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 24 horas.

Es posible que la organización tenga un valor de duración de destrucción mínimo programado por las políticas de la organización. Para obtener más información, consulta Destrucción de las teclas de control.

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

Console

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

    Ir a Key Management

  2. Haz clic en el nombre del llavero de claves para el que crearás la clave.

  3. Haz clic en Crear clave.

  4. Establece la configuración de la clave para tu aplicación.

  5. Haz clic en Configuración adicional.

  6. En Duración del estado "Programada para destrucción", elige la cantidad de días que la clave permanecerá programada para su destrucción antes de destruirse de forma permanente.

  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 Google Cloud CLI.

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

Reemplaza lo siguiente:

  • KEY_NAME: el nombre de la clave.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • PURPOSE: Es el propósito de la clave, por ejemplo, encryption.
  • DURATION: Es la cantidad de tiempo que la clave debe permanecer en el estado programado para destrucción antes de destruirse permanentemente.

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 24 horas para todas las claves, a menos que tengas requisitos regulatorios o de aplicaciones específicos que requieran un valor diferente.

Crear una clave asimétrica

Crear una clave de desencriptación asimétrica

Sigue estos pasos para crear una clave de desencriptación asimétrica en la ubicación y el llavero de claves especificados. Estos ejemplos se pueden adaptar para especificar un algoritmo o un nivel de protección diferente. 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 de clave inicial tiene un estado de Generación pendiente. Cuando el estado cambie a Enabled, podrás usar la clave. Para obtener más información sobre los estados de la versión de clave, consulta Estados de la versión de clave.

Console

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

    Ir a Key Management

  2. Haz clic en el nombre del llavero de claves para el que crearás la clave.

  3. Haz clic en Crear clave.

  4. En Nombre de la clave, ingresa un nombre.

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

  6. En Material de clave, selecciona Clave generada.

  7. En Propósito, selecciona Desencriptación asimétrica.

  8. En Algorithm, selecciona 3072 bit RSA - OAEP Padding - SHA256 Digest. Puedes cambiar este valor en versiones de claves futuras.

  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 Google Cloud CLI.

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

Reemplaza lo siguiente:

  • KEY_NAME: el nombre de la clave.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • ALGORITHM: Es el algoritmo que se usará para la clave, por ejemplo, rsa-decrypt-oaep-3072-sha256. Para obtener una lista de los algoritmos de encriptación asimétrica compatibles, consulta Algoritmos de encriptación asimétrica.

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 configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


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 configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para 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 configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para 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 configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para 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 obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para 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 configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para 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 configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para 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 un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.

Llama a CryptoKey.create para crear una clave de desencriptación asimétrica.

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"}}'

Reemplaza lo siguiente:

  • PROJECT_ID: Es el ID del proyecto que contiene el llavero de claves.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • KEY_NAME: el nombre de la clave.
  • ALGORITHM: Es el algoritmo que se usará para la clave, por ejemplo, RSA_DECRYPT_OAEP_3072_SHA256. Para obtener una lista de los algoritmos de criptografía asimétrica compatibles, consulta Algoritmos de criptografía asimétrica.

Crear una clave de firma asimétrica

Sigue estos pasos para crear una clave de firma asimétrica en el llavero de claves y la ubicación especificados. Estos ejemplos se pueden adaptar para especificar un algoritmo o un nivel de protección diferente. 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 de clave inicial tiene un estado de Generación pendiente. Cuando el estado cambie a Enabled, podrás usar la clave. Para obtener más información sobre los estados de la versión de clave, consulta Estados de la versión de clave.

Console

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

    Ir a Key Management

  2. Haz clic en el nombre del llavero de claves para el que crearás la clave.

  3. Haz clic en Crear clave.

  4. En Nombre de la clave, ingresa un nombre.

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

  6. En Material de clave, selecciona Clave generada.

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

  8. En Algorithm, selecciona Elliptic Curve P-256 - SHA256 Digest. Puedes cambiar este valor en versiones de clave futuras.

  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 Google Cloud CLI.

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

Reemplaza lo siguiente:

  • KEY_NAME: el nombre de la clave.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • ALGORITHM: Es el algoritmo que se usará para la clave, por ejemplo, ec-sign-p256-sha256. Para obtener una lista de los algoritmos compatibles, consulta Algoritmos de firma asimétrica.

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 configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


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 configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para 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 configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para 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 configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para 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 obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para 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 configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para 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 configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para 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 un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.

Llama a CryptoKey.create para crear una clave de firma asimétrica.

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"}}'

Reemplaza lo siguiente:

  • PROJECT_ID: Es el ID del proyecto que contiene el llavero de claves.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • KEY_NAME: el nombre de la clave.
  • ALGORITHM: Es el algoritmo que se usará para la clave, por ejemplo, EC_SIGN_P256_SHA256. Para obtener una lista de los algoritmos compatibles, consulta Algoritmos de firma asimétrica.

Recupera la clave pública

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

La clave pública se encuentra en el formato de correo electrónico con privacidad mejorada (PEM). Para obtener más información, consulta las secciones sobre consideraciones generales y codificación textual de la información de la clave pública del sujeto de RFC 7468.

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

Console

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

    Ir a Key Management

  2. Haz clic en el nombre del llavero de claves que contiene la clave asimétrica para la que quieres recuperar la clave pública.

  3. Haz clic en el nombre de la clave cuya clave pública deseas recuperar.

  4. En la fila que corresponde a la versión de clave para la que quieres recuperar la clave pública, haz clic en Ver más .

  5. Haz clic en Obtener clave pública.

  6. La clave pública se muestra en el mensaje. Puedes copiar la clave pública en el portapapeles. Para descargar la clave pública, haz clic en Descargar.

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

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

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

KEY_RING-KEY_NAME-KEY_VERSION.pub

Cada parte del nombre del 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 Google Cloud CLI.

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

Reemplaza lo siguiente:

  • KEY_VERSION: Es el número de versión de la clave.
  • KEY_NAME: el nombre de la clave.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • OUTPUT_FILE_PATH: Es la ruta de acceso en la que deseas guardar el archivo de claves públicas, 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 configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


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 configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para 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 configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para 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 configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para 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 obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para 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 configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para 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 configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para 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 un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.

Recupera la clave pública mediante una llamada 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" \
    --request "GET" \
    --header "authorization: Bearer TOKEN"

Reemplaza lo siguiente:

  • PROJECT_ID: Es el ID del proyecto que contiene el llavero de claves.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • KEY_NAME: el nombre de la clave.
  • KEY_VERSION: Es el número de versión de la clave.

El resultado debería 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": "SOFTWARE"
}

Convierte una clave pública a formato JWK

Cloud KMS te permite recuperar una clave pública en formato PEM. Algunas aplicaciones pueden requerir otros formatos de clave, como la clave web JSON (JWK). Para obtener más información sobre el formato JWK, consulta RFC 7517.

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

Go

Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para 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 configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para 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 configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para 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)

Controla el acceso a claves asimétricas

Un firmante o validador requiere el permiso o función adecuados para la clave asimétrica.

  • Para un usuario o servicio que realizará las firmas, otorga el permiso cloudkms.cryptoKeyVersions.useToSign sobre la clave asimétrica.

  • Para un usuario o servicio que recuperará la clave pública, otorga el permiso cloudkms.cryptoKeyVersions.viewPublicKey sobre la clave asimétrica. Para la validación de la firma se necesita la clave pública.

Para conocer más sobre los permisos y las funciones en esta versión de Cloud KMS, visita Permisos y funciones.

Cómo crear una clave de firma MAC

Console

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

    Ir a Key Management

  2. Haz clic en el nombre del llavero de claves para el que crearás la clave.

  3. Haz clic en Crear clave.

  4. En Nombre de la clave, ingresa un nombre.

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

  6. En Material de clave, selecciona Clave generada.

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

  8. Opcional: Para 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 Google Cloud CLI.

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

Reemplaza lo siguiente:

  • KEY_NAME: el nombre de la clave.
  • KEY_RING: Es el nombre del llavero de claves que contiene la clave.
  • LOCATION: Es la ubicación de Cloud KMS del llavero de claves.
  • ALGORITHM: Es el algoritmo de firma HMAC, por ejemplo, hmac-sha256. Para ver todos los algoritmos HMAC compatibles, consulta Algoritmos de firma HMAC.
  • PROTECTION_LEVEL: Es el nivel de protección de la clave, por ejemplo, hsm. Puedes omitir la marca --protection-level para 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 configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


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 configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para 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 configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para 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 configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para 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 obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para 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 configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para 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 configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para 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 un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de 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" }}'

Reemplaza lo siguiente:

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

¿Qué sigue?