Crea claves simétricas

Cloud Key Management Service usa una jerarquía de objetos, en la que una clave pertenece a un llavero de claves, el cual reside en una ubicación específica.

Crea un llavero de claves

La ubicación y el nombre definen a un llavero de claves.

Console

  1. Ve a la página Claves criptográficas en GCP Console.
    Ir a la página Claves criptográficas

  2. Haz clic en Crear llavero de claves.

  3. En el campo Nombre del llavero de claves, ingresa el nombre de tu llavero de claves.

  4. En el menú desplegable Ubicación, selecciona una ubicación.
    Tu página Crear llavero de claves debe ser similar a la que se muestra a continuación:

    Crea una clave

  5. Haz clic en Crear.

Línea de comandos

Crea un llavero de claves nuevo con el nombre [KEYRING_NAME] en la ubicación [LOCATION].

gcloud kms keyrings create [KEYRING_NAME] --location [LOCATION]

C#

      public static void CreateKeyRing(string projectId, string locationId, string keyRingId)
      {
          KeyManagementServiceClient client = KeyManagementServiceClient.Create();

          // The location in which to create the key ring.
          LocationName locationName = new LocationName(projectId, locationId);

          // Initial values for the KeyRing (currently unused).
          KeyRing keyRing = new KeyRing();

          KeyRing result = client.CreateKeyRing(locationName, keyRingId, keyRing);
          Console.Write($"Created Key Ring: {result.Name}");
      }

Go

import (
	"context"
	"fmt"
	"io"

	cloudkms "cloud.google.com/go/kms/apiv1"
	kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

// createKeyRing creates a new ring to store keys on KMS.
func createKeyRing(w io.Writer, parent, keyRingID string) error {
	// parent := "projects/PROJECT_ID/locations/global/"
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("cloudkms.NewKeyManagementClient: %v", err)
	}
	// Build the request.
	req := &kmspb.CreateKeyRingRequest{
		Parent:    parent,
		KeyRingId: keyRingID,
	}
	// Call the API.
	result, err := client.CreateKeyRing(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateKeyRing: %v", err)
	}
	fmt.Fprintf(w, "Created key ring: %s", result)
	return nil
}

Java


/**
 * Creates a new key ring with the given id.
 */
public static KeyRing createKeyRing(String projectId, String locationId, String keyRingId)
    throws IOException {
  // Create the Cloud KMS client.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the location associated with the KeyRing.
    String parent = LocationName.format(projectId, locationId);

    // Create the KeyRing for your project.
    KeyRing keyRing = client.createKeyRing(parent, keyRingId, KeyRing.newBuilder().build());

    return keyRing;
  }
}

Node.js

async function createKeyRing(
  projectId = 'YOUR_PROJECT_ID', // Your GCP projectId
  keyRingId = 'my-new-key-ring' // Name of the new key ring
) {
  // The location of the new key ring, e.g. "global"
  const locationId = 'global';

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // Get the full path to the parent
  const parent = client.locationPath(projectId, locationId);

  // Creates a new key ring
  const [result] = await client.createKeyRing({parent, keyRingId});
  console.log(`Key ring ${result.name} created.`);
}

PHP

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

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';

$kms = new KeyManagementServiceClient();

// The resource name of the KeyRing.
$locationName = $kms->locationName($projectId, $locationId);

$keyRing = new KeyRing();

// Create the CryptoKey for your project.
$newKeyRing = $kms->createKeyRing(
    $locationName,
    $keyRingId,
    $keyRing
);

printf('Created keyRing %s' . PHP_EOL, $keyRingId);

Python

def create_key_ring(project_id, location_id, key_ring_id):
    """Creates a KeyRing in the given location (e.g. global)."""

    from google.cloud import kms_v1

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the location associated with the KeyRing.
    parent = client.location_path(project_id, location_id)

    # The keyring object template
    keyring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    keyring = {'name': keyring_name}

    # Create a KeyRing
    response = client.create_key_ring(parent, key_ring_id, keyring)

    print('Created KeyRing {}.'.format(response.name))
    return response

Ruby

# project_id  = "Your Google Cloud project ID"
# key_ring_id = "The ID of the new key ring"
# location_id = "The location of the new key ring"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The location associated with the key ring
location = CloudKMS::KeyManagementServiceClient.location_path project_id, location_id

# KeyRing creation parameters (currently unused)
key_ring_spec = CloudKMS::KeyRing.new

# Create a key ring for your project
key_ring = client.create_key_ring location, key_ring_id, key_ring_spec

puts "Created key ring #{key_ring_id}"

Crea una clave

Las claves deben crearse en un llavero de claves.

Console

  1. Ve a la página Claves criptográficas en GCP Console.
    Ir a la página Claves criptográficas

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

  3. Haz clic en Crear clave.

  4. Ingresa el nombre en el campo Nombre de la clave.

  5. Acepta los valores predeterminados de Período de rotación y A partir del, o define un período de rotación de clave y una fecha de inicio si quieres usar valores diferentes.

  6. Opcionalmente, si deseas agregar etiquetas a tu clave, haz clic en Agregar etiqueta en el campo Etiquetas.
    Tu página Crear clave debe ser similar a la que se muestra a continuación:

    Crea una clave

  7. Haz clic en Crear.

Línea de comandos

Crea una clave [KEY_NAME] nueva para el llavero de claves [KEYRING_NAME].

gcloud kms keys create [KEY_NAME] --location [LOCATION] \
  --keyring [KEYRING_NAME] --purpose encryption

C#

      public static void CreateCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId)
      {
          KeyManagementServiceClient client = KeyManagementServiceClient.Create();

          // The KeyRing in which to create the CryptoKey.
          KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

          CryptoKey cryptoKeyToCreate = new CryptoKey();
          cryptoKeyToCreate.Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt;

          CryptoKey result = client.CreateCryptoKey(keyRingName, cryptoKeyId, cryptoKeyToCreate);
          Console.Write($"Created Crypto Key: {result.Name}");
      }

Go

import (
	"context"
	"fmt"
	"io"

	cloudkms "cloud.google.com/go/kms/apiv1"
	kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

// createCryptoKey creates a new symmetric encrypt/decrypt key on KMS.
func createCryptoKey(w io.Writer, keyRingName, keyID string) error {
	// keyRingName := "projects/PROJECT_ID/locations/global/keyRings/RING_ID"
	// keyID := "key-" + strconv.Itoa(int(time.Now().Unix()))
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("cloudkms.NewKeyManagementClient: %v", err)
	}

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      keyRingName,
		CryptoKeyId: keyID,
		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("CreateCryptoKey: %v", err)
	}
	fmt.Fprintf(w, "Created crypto key. %s", result)
	return nil
}

Java


/**
 * Creates a new crypto key with the given id.
 */
public static CryptoKey createCryptoKey(String projectId, String locationId, String keyRingId,
    String cryptoKeyId)
    throws IOException {

  // Create the Cloud KMS client.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // The resource name of the location associated with the KeyRing.
    String parent = KeyRingName.format(projectId, locationId, keyRingId);

    // This will allow the API access to the key for encryption and decryption.
    CryptoKey cryptoKey = CryptoKey.newBuilder()
        .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
        .build();

    // Create the CryptoKey for your project.
    CryptoKey createdKey = client.createCryptoKey(parent, cryptoKeyId, cryptoKey);

    return createdKey;
  }
}

Node.js

async function createCryptoKey(
  projectId = 'your-project-id', // Your GCP Project Id
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key' // Name of the crypto key
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the new crypto key's key ring, e.g. "global"
  const locationId = 'global';

  const parent = client.keyRingPath(projectId, locationId, keyRingId);

  // Creates a new key ring
  const [cryptoKey] = await client.createCryptoKey({
    parent,
    cryptoKeyId,
    cryptoKey: {
      // This will allow the API access to the key for encryption and decryption
      purpose: 'ENCRYPT_DECRYPT',
    },
  });
  console.log(`Key ${cryptoKey.name} created.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';
// $cryptoKeyId = 'The KMS key ID';

$kms = new KeyManagementServiceClient();

// The resource name of the KeyRing.
$keyRingName = $kms->keyRingName($projectId, $locationId, $keyRingId);

$cryptoKey = new CryptoKey();
// This will allow the API access to the key for encryption and decryption.
$cryptoKey->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT);

// Create the CryptoKey for your project.
$newKey = $kms->createCryptoKey(
    $keyRingName,
    $cryptoKeyId,
    $cryptoKey
);

printf('Created cryptoKey %s in keyRing %s' . PHP_EOL, $cryptoKeyId, $keyRingId);

Python

def create_crypto_key(project_id, location_id, key_ring_id, crypto_key_id):
    """Creates a CryptoKey within a KeyRing in the given location."""

    from google.cloud import kms_v1
    from google.cloud.kms_v1 import enums

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the KeyRing associated with the CryptoKey.
    parent = client.key_ring_path(project_id, location_id, key_ring_id)

    # Create the CryptoKey object template
    purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    crypto_key = {'purpose': purpose}

    # Create a CryptoKey for the given KeyRing.
    response = client.create_crypto_key(parent, crypto_key_id, crypto_key)

    print('Created CryptoKey {}.'.format(response.name))
    return response

Ruby

# project_id    = "Your Google Cloud project ID"
# location_id   = "The location of the key ring"
# key_ring_id   = "The ID of the key ring"
# crypto_key_id = "The ID of the new crypto key"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The key ring to use
key_ring =
  CloudKMS::KeyManagementServiceClient.key_ring_path project_id, location_id, key_ring_id

# CryptoKey creation parameters
crypto_key_spec = CloudKMS::CryptoKey.new
crypto_key_spec.purpose = CloudKMS::CryptoKey::CryptoKeyPurpose::ENCRYPT_DECRYPT

# Create a crypto key in the key ring
crypto_key = client.create_crypto_key key_ring, crypto_key_id, crypto_key_spec

puts "Created crypto key #{crypto_key_id}"

Define un período de rotación de clave y una fecha de inicio

Se puede crear una clave con un período de rotación específico, que es el tiempo que transcurre antes de que se genere automáticamente una nueva versión de clave. También se puede crear una clave con un período de rotación siguiente específico.

Console

Cuando usas Google Cloud Platform Console para crear una clave, pero no especificas un período de rotación ni cuándo debe hacerse la próxima rotación, Cloud KMS determina estos ajustes de forma automática.

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

  1. Haz clic en el menú desplegable Período de rotación y selecciona un valor para el período.
  2. Haz clic en la fecha en el campo A partir del y selecciona una fecha para la siguiente rotación.

Línea de comandos

gcloud kms keys create [KEY_NAME] --location [LOCATION] \
  --keyring [KEYRING_NAME] \
  --purpose encryption \
  --rotation-period [ROTATION_PERIOD] \
  --next-rotation-time [NEXT_ROTATION_TIME]

Windows cmd.exe

gcloud kms keys create [KEY_NAME] --location [LOCATION] ^
  --keyring [KEYRING_NAME] ^
  --purpose encryption  ^
  --rotation-period [ROTATION_PERIOD] ^
  --next-rotation-time [NEXT_ROTATION_TIME]

PowerShell

gcloud kms keys create [KEY_NAME] --location [LOCATION] `
  --keyring [KEYRING_NAME] `
  --purpose encryption `
  --rotation-period [ROTATION_PERIOD] `
  --next-rotation-time [NEXT_ROTATION_TIME]

Crea versiones de claves nuevas de forma manual

Además de la rotación automática, puedes rotar la claves de forma manual. Para obtener más detalles, consulta Rotación de claves.

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...

Documentación de Cloud KMS