Rota una clave

En esta página, se muestra cómo rotar una clave de forma automática o manual. Para obtener más información sobre la rotación de claves en general, consulta Rotación de claves.

Funciones obligatorias

Si quieres obtener los permisos que necesitas para rotar las claves, pídele a tu administrador que te otorgue los siguientes roles de IAM en tu clave:

Si quieres obtener más información para otorgar funciones, consulta Administra el acceso.

Estos roles predefinidos contienen los permisos necesarios para rotar las claves. Para ver los permisos exactos que son necesarios, expande la sección Permisos requeridos:

Permisos necesarios

Se requieren los siguientes permisos para rotar las claves:

  • Cambia la versión de la clave primaria: cloudkms.cryptoKeys.update
  • Cambia o inhabilita la rotación automática: cloudkms.cryptoKeys.update
  • Crear versión de clave nueva: cloudkms.cryptoKeyVersions.create
  • Inhabilita las versiones de claves anteriores: cloudkms.cryptoKeyVersions.update
  • Vuelve a encriptar los datos:
    • cloudkms.cryptoKeyVersions.useToDecrypt
    • cloudkms.cryptoKeyVersions.useToEncrypt

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

Un solo usuario con una función personalizada que contenga todos estos permisos puede rotar las claves y volver a encriptar datos por su cuenta. Los usuarios con la función de administrador de Cloud KMS y de encriptador o desencriptador de CryptoKey de Cloud KMS pueden trabajar juntos para rotar las claves y volver a encriptar los datos. Sigue el principio de privilegio mínimo cuando asignes funciones. Para obtener más detalles, consulta Permisos y roles.

Cuando rotas una clave, los datos que se encriptaron con versiones de claves anteriores no se vuelven a encriptar de manera automática. Para obtener más información, consulta desencriptar y volver a encriptar. La rotación de una clave no inhabilita ni destroy de forma automática ninguna versión de clave existente.

Cómo configurar la rotación automática

Para configurar la rotación automática cuando creas una clave nueva, haz lo siguiente:

Console

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

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

  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 se crea 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 para rotar 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 para rotar 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 configurar la rotación automática en una clave existente, haz lo siguiente:

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves que contiene la clave para la que deseas agregar un programa de rotación.

  3. Haz clic en la clave a la que deseas agregar un programa de rotación.

  4. En el encabezado, haz clic en Editar período de rotación.

  5. En el mensaje, elige valores nuevos para los campos Período de rotación y A partir de.

  6. En la ventana, haz clic en Guardar.

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 update KEY_NAME \
    --location LOCATION \
    --keyring KEY_RING \
    --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 para rotar 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 UpdateKeyAddRotationSample
{
    public CryptoKey UpdateKeyAddRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            // Provide the name of the key to update.
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),

            // 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(),
            }
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "rotation_period", "next_rotation_time" },
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        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"
	fieldmask "google.golang.org/genproto/protobuf/field_mask"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// addRotationSchedule updates a key to add a rotation schedule. If the key
// already has a rotation schedule, it is overwritten.
func addRotationSchedule(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-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.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			// Provide the name of the key to update
			Name: name,

			// 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(),
			},
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"rotation_period", "next_rotation_time"},
		},
	}

	// Call the API.
	result, err := client.UpdateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}
	fmt.Fprintf(w, "Updated 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.CryptoKeyName;
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.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;
import java.time.temporal.ChronoUnit;

public class UpdateKeyAddRotation {

  public void updateKeyAddRotation() 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 keyId = "my-key";
    updateKeyAddRotation(projectId, locationId, keyRingId, keyId);
  }

  // Update a key to add or change a rotation schedule.
  public void updateKeyAddRotation(
      String projectId, String locationId, String keyRingId, String keyId) 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 name from the project, location, and key ring.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // 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 update with a rotation schedule.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setName(cryptoKeyName.toString())
              .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();

      // Construct the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

      // Update the key.
      CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated key %s%n", updatedKey.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 keyId = 'my-key';
// const versionId = '123';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyAddRotation() {
  const [key] = await client.updateCryptoKey({
    cryptoKey: {
      name: keyName,

      // 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,
      },
    },
    updateMask: {
      paths: ['rotation_period', 'next_rotation_time'],
    },
  });

  console.log(`Updated rotation for: ${key.name}`);
  return key;
}

return updateKeyAddRotation();

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\CryptoKey;
use Google\Cloud\Kms\V1\UpdateCryptoKeyRequest;
use Google\Protobuf\Duration;
use Google\Protobuf\FieldMask;
use Google\Protobuf\Timestamp;

function update_key_add_rotation(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key.
    $key = (new CryptoKey())
        ->setName($keyName)

        // 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)
        );

    // Create the field mask.
    $updateMask = (new FieldMask())
        ->setPaths(['rotation_period', 'next_rotation_time']);

    // Call the API.
    $updateCryptoKeyRequest = (new UpdateCryptoKeyRequest())
        ->setCryptoKey($key)
        ->setUpdateMask($updateMask);
    $updatedKey = $client->updateCryptoKey($updateCryptoKeyRequest);
    printf('Updated key: %s' . PHP_EOL, $updatedKey->getName());

    return $updatedKey;
}

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 update_key_add_rotation(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Add a rotation schedule to an existing 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').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    key = {
        "name": key_name,
        "rotation_period": {
            "seconds": 60 * 60 * 24 * 30  # Rotate the key every 30 days.
        },
        "next_rotation_time": {
            "seconds": int(time.time())
            + 60 * 60 * 24  # Start the first rotation in 24 hours.
        },
    }

    # Build the update mask.
    update_mask = {"paths": ["rotation_period", "next_rotation_time"]}

    # Call the API.
    updated_key = client.update_crypto_key(
        request={"crypto_key": key, "update_mask": update_mask}
    )
    print(f"Updated key: {updated_key.name}")
    return updated_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"
# key_id      = "my-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the key.
key = {
  name:               key_name,

  # 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
  }
}

# Build the field mask.
update_mask = { paths: ["rotation_period", "next_rotation_time"] }

# Call the API.
updated_key = client.update_crypto_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_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 actualizar una clave, usa el método CryptoKey.patch:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \
    --request "PATCH" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'

Reemplaza lo siguiente:

  • ROTATION_PERIOD: Es el intervalo para rotar 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.

Rota una clave de forma manual

Primero, crea una versión de clave nueva:

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves que contiene la clave para la que crearás una versión de clave nueva.

  3. Haz clic en la clave para la que crearás una versión de clave nueva.

  4. En el encabezado, haz clic en Rotar.

  5. En el mensaje, haz clic en Rotar para confirmar.

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 create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION

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.

A las versiones de claves se les asigna un número de manera secuencial.

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 CreateKeyVersionSample
{
    public CryptoKeyVersion CreateKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion { };

        // Call the API.
        CryptoKeyVersion result = client.CreateCryptoKeyVersion(keyName, keyVersion);

        // 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"
)

// createKeyVersion creates a new key version for the given key.
func createKeyVersion(w io.Writer, parent string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-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.CreateCryptoKeyVersionRequest{
		Parent: parent,
	}

	// Call the API.
	result, err := client.CreateCryptoKeyVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key version: %w", err)
	}
	fmt.Fprintf(w, "Created key version: %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.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class CreateKeyVersion {

  public void createKeyVersion() 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 keyId = "my-key";
    createKeyVersion(projectId, locationId, keyRingId, keyId);
  }

  // Create a new key version.
  public void createKeyVersion(String projectId, String locationId, String keyRingId, String keyId)
      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.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build the key version to create.
      CryptoKeyVersion keyVersion = CryptoKeyVersion.newBuilder().build();

      // Create the key.
      CryptoKeyVersion createdVersion = client.createCryptoKeyVersion(cryptoKeyName, keyVersion);
      System.out.printf("Created key version %s%n", createdVersion.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 keyId = 'my-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function createKeyVersion() {
  const [version] = await client.createCryptoKeyVersion({
    parent: keyName,
  });

  console.log(`Created key version: ${version.name}`);
  return version;
}

return createKeyVersion();

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\CreateCryptoKeyVersionRequest;
use Google\Cloud\Kms\V1\CryptoKeyVersion;

function create_key_version(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
): CryptoKeyVersion {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key version.
    $version = new CryptoKeyVersion();

    // Call the API.
    $createCryptoKeyVersionRequest = (new CreateCryptoKeyVersionRequest())
        ->setParent($keyName)
        ->setCryptoKeyVersion($version);
    $createdVersion = $client->createCryptoKeyVersion($createCryptoKeyVersionRequest);
    printf('Created key version: %s' . PHP_EOL, $createdVersion->getName());

    return $createdVersion;
}

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_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new version of the given 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 for which to create a new version (e.g. 'my-key').

    Returns:
        CryptoKeyVersion: Cloud KMS key version.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # Build the key version.
    version = {}

    # Call the API.
    created_version = client.create_crypto_key_version(
        request={"parent": key_name, "crypto_key_version": version}
    )
    print(f"Created key version: {created_version.name}")
    return created_version

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"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the version.
version = {}

# Call the API.
created_version = client.create_crypto_key_version parent: key_name, crypto_key_version: version
puts "Created key version: #{created_version.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 rotar una clave de forma manual, primero crea una versión nueva mediante una llamada al método CryptoKeyVersions.create.

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

Este comando crea una versión de clave nueva, pero no la configura como la versión principal.

Para establecer tu versión de clave nueva como la primaria, consulta Configura una versión existente como la versión de clave primaria.

Si es necesario, vuelve a encriptar los datos que se encriptaron con la versión de clave anterior.

Configura una versión existente como la versión de clave primaria

A fin de establecer una versión de clave diferente como la versión principal de una clave, actualízala con la nueva información de la versión principal. Se debe habilitar una versión de clave antes de configurarla como la versión principal.

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves que contiene la clave cuya versión principal deseas actualizar.

  3. Haz clic en la clave cuya versión principal deseas actualizar.

  4. En la fila correspondiente a la versión de clave que deseas convertir en principal, haz clic en Ver más .

  5. Haz clic en Crear versión principal en el menú.

  6. En el mensaje de confirmación, haz clic en Convertir en principal.

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 update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --primary-version KEY_VERSION

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.
  • KEY_VERSION: Es el número de la versión de la clave primaria nueva.

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 UpdateKeySetPrimarySample
{
    public CryptoKey UpdateKeySetPrimary(
      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 name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Call the API.
        CryptoKey result = client.UpdateCryptoKeyPrimaryVersion(keyName, keyVersionId);

        // Return the updated key.
        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"
)

// updateKeySetPrimary updates the primary key version on a Cloud KMS key.
func updateKeySetPrimary(w io.Writer, name, version string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"
	// version := "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.UpdateCryptoKeyPrimaryVersionRequest{
		Name:               name,
		CryptoKeyVersionId: version,
	}

	// Call the API.
	result, err := client.UpdateCryptoKeyPrimaryVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}
	fmt.Fprintf(w, "Updated key primary: %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.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class UpdateKeySetPrimary {

  public void updateKeySetPrimary() 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 keyId = "my-key";
    String keyVersionId = "123";
    updateKeySetPrimary(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Update a key's primary version.
  public void updateKeySetPrimary(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      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 name from the project, location, key ring, and keyId.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Create the key.
      CryptoKey createdKey = client.updateCryptoKeyPrimaryVersion(cryptoKeyName, keyVersionId);
      System.out.printf("Updated key primary version %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 keyId = 'my-key';
// const versionId = '123';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeySetPrimary() {
  const [key] = await client.updateCryptoKeyPrimaryVersion({
    name: keyName,
    cryptoKeyVersionId: versionId,
  });

  console.log(`Set primary to ${versionId}`);
  return key;
}

return updateKeySetPrimary();

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\UpdateCryptoKeyPrimaryVersionRequest;

function update_key_set_primary(
    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 name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Call the API.
    $updateCryptoKeyPrimaryVersionRequest = (new UpdateCryptoKeyPrimaryVersionRequest())
        ->setName($keyName)
        ->setCryptoKeyVersionId($versionId);
    $updatedKey = $client->updateCryptoKeyPrimaryVersion($updateCryptoKeyPrimaryVersionRequest);
    printf('Updated primary %s to %s' . PHP_EOL, $updatedKey->getName(), $versionId);

    return $updatedKey;
}

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 parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Call the API.
updated_key = client.update_crypto_key_primary_version name: key_name, crypto_key_version_id: version_id
puts "Updated primary #{updated_key.name} to #{version_id}"

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 update_key_set_primary(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.CryptoKey:
    """
    Update the primary version of a 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 make primary (e.g. '2').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # Call the API.
    updated_key = client.update_crypto_key_primary_version(
        request={"name": key_name, "crypto_key_version_id": version_id}
    )
    print(f"Updated {updated_key.name} primary to {version_id}")
    return updated_key

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 cambiar la versión de la clave primaria, llama al método CryptoKey.updatePrimaryVersion.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME:updatePrimaryVersion" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"cryptoKeyVersionId": "KEY_VERSION"}'

Reemplaza lo siguiente:

  • PROJECT_ID: 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 la versión de la clave primaria nueva.

Cuando cambias la versión de la clave primaria, el cambio suele ser coherente en 1 minuto. Sin embargo, en casos excepcionales, este cambio puede tardar hasta 3 horas en propagarse. Durante este tiempo, es posible que la versión principal anterior se use para encriptar datos. Para obtener más información, consulta Coherencia de recursos de Cloud KMS.

Inhabilita la rotación automática

Para inhabilitar la rotación automática de una clave, borra el programa de rotación de la clave:

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves que contiene la clave para la que deseas quitar la programación de rotación.

  3. Haz clic en la clave de la que deseas quitar el programa de rotación.

  4. En el encabezado, haz clic en Editar período de rotación.

  5. En el mensaje, haz clic en el campo Período de rotación y selecciona Nunca (rotación manual).

  6. En la ventana, haz clic en Guardar.

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 update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --remove-rotation-schedule

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.

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 UpdateKeyRemoveRotationSample
{
    public CryptoKey UpdateKeyRemoveRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),
            RotationPeriod = null,
            NextRotationTime = null,
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "rotation_period", "next_rotation_time" },
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        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"
	fieldmask "google.golang.org/genproto/protobuf/field_mask"
)

// removeRotationSchedule updates a key to remove a rotation schedule, if one
// exists.
func removeRotationSchedule(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-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.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			// Provide the name of the key to update
			Name: name,

			// Remove any rotation fields.
			RotationSchedule: nil,
			NextRotationTime: nil,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"rotation_period", "next_rotation_time"},
		},
	}

	// Call the API.
	result, err := client.UpdateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}
	fmt.Fprintf(w, "Updated 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.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateKeyRemoveRotation {

  public void updateKeyRemoveRotation() 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 keyId = "my-key";
    updateKeyRemoveRotation(projectId, locationId, keyRingId, keyId);
  }

  // Update a key to remove all labels.
  public void updateKeyRemoveRotation(
      String projectId, String locationId, String keyRingId, String keyId) 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 name from the project, location, key ring, and keyId.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build an empty key with no labels.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setName(cryptoKeyName.toString())
              .clearRotationPeriod()
              .clearNextRotationTime()
              .build();

      // Construct the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

      // Create the key.
      CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated 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 keyId = 'my-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyRemoveRotation() {
  const [key] = await client.updateCryptoKey({
    cryptoKey: {
      name: keyName,
      rotationPeriod: null,
      nextRotationTime: null,
    },
    updateMask: {
      paths: ['rotation_period', 'next_rotation_time'],
    },
  });

  console.log(`Removed rotation for: ${key.name}`);
  return key;
}

return updateKeyRemoveRotation();

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\CryptoKey;
use Google\Cloud\Kms\V1\UpdateCryptoKeyRequest;
use Google\Protobuf\FieldMask;

function update_key_remove_rotation(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key.
    $key = (new CryptoKey())
        ->setName($keyName);

    // Create the field mask.
    $updateMask = (new FieldMask())
        ->setPaths(['rotation_period', 'next_rotation_time']);

    // Call the API.
    $updateCryptoKeyRequest = (new UpdateCryptoKeyRequest())
        ->setCryptoKey($key)
        ->setUpdateMask($updateMask);
    $updatedKey = $client->updateCryptoKey($updateCryptoKeyRequest);
    printf('Updated key: %s' . PHP_EOL, $updatedKey->getName());

    return $updatedKey;
}

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"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the key.
key = {
  name:               key_name,
  rotation_period:    nil,
  next_rotation_time: nil
}

# Build the field mask.
update_mask = { paths: ["rotation_period", "next_rotation_time"] }

# Call the API.
updated_key = client.update_crypto_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_key.name}"

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 update_key_remove_rotation(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Remove a rotation schedule from an existing 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').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    key = {"name": key_name}

    # Build the update mask.
    update_mask = {"paths": ["rotation_period", "next_rotation_time"]}

    # Call the API.
    updated_key = client.update_crypto_key(
        request={"crypto_key": key, "update_mask": update_mask}
    )
    print(f"Updated key: {updated_key.name}")
    return updated_key

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 actualizar una clave, usa el método CryptoKey.patch:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \
    --request "PATCH" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"rotationPeriod": null, "nextRotationTime": null}'

Para obtener detalles adicionales sobre rotationPeriod y nextRotationTime, consulta keyRings.cryptoKeys.

Rota una clave externa

Rota una clave externa coordinada

Puedes configurar la rotación automática para claves externas coordinadas simétricas. También puedes crear manualmente una nueva versión de la clave para claves externas coordinadas simétricas o asimétricas.

La rotación o creación de una versión de clave nueva hace que todos los datos recién creados protegidos con esa clave se encripten con la nueva versión de clave. Los datos protegidos con una versión de clave anterior no se vuelven a encriptar. Como resultado, el administrador de claves externo debe seguir haciendo que el material de claves de la versión de clave anterior esté disponible para su uso.

Para crear una versión de clave nueva de una clave externa coordinada, 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. Selecciona el llavero de claves y, luego, la clave.

  3. Haz clic en Crear versión. Un mensaje indica que tu versión de clave nueva se generará tanto en Cloud KMS como en tu EKM. Si ves un campo Ruta de acceso de la clave o URI de la clave, significa que la clave seleccionada no es una clave externa coordinada.

  4. Para confirmar que deseas crear una versión de clave nueva, haz clic en Crear versión.

La versión de clave nueva aparece con el estado Generación pendiente. En el caso de las claves simétricas, las versiones de claves creadas de forma manual no se configuran automáticamente como la versión de clave primaria. Puedes configurar tu versión de clave nueva como principal.

gcloud CLI

Para crear una nueva versión de clave simétrica y configurarla como la versión de clave primaria, usa el comando kms keys versions create con la marca --primary:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --primary

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.

Para crear una versión de clave asimétrica nueva o una versión de clave simétrica nueva que no sea la versión de clave primaria, usa el comando kms keys versions create:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION

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.

Rota un Cloud EKM administrado de forma manual mediante una clave de VPC

Primero, rota el material de la clave externa en tu administrador de claves externo. Si eso da como resultado una ruta de acceso de clave nueva, debes rotar o crear una versión de clave de Cloud EKM nueva con la ruta de acceso de la clave nueva. En el caso de las claves de encriptación simétricas, rota la clave de Cloud EKM y especifica la ruta de la clave nueva desde el administrador de claves externo. En el caso de las claves asimétricas, crea una versión de clave nueva y especifica la ruta de acceso de la clave nueva.

La rotación o creación de una versión de clave nueva hace que todos los datos recién creados protegidos con esa clave se encripten con la nueva versión de clave. Los datos protegidos con una versión de clave anterior no se vuelven a encriptar. Como resultado, el administrador de claves externo debe seguir haciendo que el material de claves de la versión de clave anterior esté disponible para su uso.

Si el material de la clave en el sistema asociado de administración de claves externo no cambia, pero la ruta de la clave sí cambia, puedes actualizar la ruta externa de la clave sin rotarla.

Console

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

    Ir a Key Management

  2. Selecciona el llavero de claves y, luego, la clave.

  3. Haz clic en Rotar clave.

  4. En Key path, ingresa la ruta de acceso de la clave para la versión nueva.

  5. Haz clic en Rotar clave para confirmar.

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.

Para crear una nueva versión de clave simétrica y configurarla como la versión de clave primaria, usa el comando kms keys versions create con la marca --primary:

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --ekm-connection-key-path EXTERNAL_KEY_PATH \
    --primary

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.
  • EXTERNAL_KEY_PATH: Es la ruta a la nueva versión de la clave externa.

Para crear una versión de clave asimétrica nueva o una versión de clave simétrica nueva que no sea la versión de clave primaria, usa el comando kms keys versions create:

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --ekm-connection-key-path EXTERNAL_KEY_PATH

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.
  • EXTERNAL_KEY_PATH: Es la ruta a la nueva versión de la clave externa.

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

Una vez que la versión de clave se crea con éxito, puedes usarla como lo harías con cualquier otra versión de clave de Cloud KMS.

Rota un Cloud EKM administrado de forma manual mediante una clave de Internet

Primero, rota el material de la clave externa en tu administrador de claves externo. Si eso genera un URI nuevo, debes rotar o crear una versión de la clave de Cloud EKM nueva con el URI nuevo. En el caso de las claves de encriptación simétricas, rota la clave de Cloud EKM y especifica el URI de la clave nueva desde tu administrador de claves externo. En el caso de las claves asimétricas, crea una versión de clave nueva y especifica el URI de la clave nueva.

La rotación o creación de una versión de clave nueva hace que todos los datos recién creados protegidos con esa clave se encripten con la nueva versión de clave. Los datos protegidos con una versión de clave anterior no se vuelven a encriptar. Como resultado, el administrador de claves externo debe seguir haciendo que el material de claves de la versión de clave anterior esté disponible para su uso.

Si el material de claves del sistema asociado de administración de claves externo no cambia, pero el URI sí, puedes actualizar el URI externo de la clave sin rotar la clave.

Console

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

    Ir a Key Management

  2. Selecciona el llavero de claves y, luego, la clave.

  3. Selecciona Rotar clave para las claves simétricas o Crear versión para las claves asimétricas.

  4. Ingresa el URI de la clave nueva y, luego, selecciona Rotar clave para las claves simétricas o Crear versión para las claves asimétricas.

La versión de clave nueva se convertirá en la versión principal.

gcloud CLI

Para crear una nueva versión de clave simétrica y configurarla como la versión de clave primaria, usa el comando kms keys versions create con la marca --primary:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --external-key-uri EXTERNAL_KEY_URI \
  --primary

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.
  • EXTERNAL_KEY_URI: Es el URI de la clave de la versión de clave externa nueva.

Para crear una versión de clave asimétrica nueva o una versión de clave simétrica nueva que no sea la versión de clave primaria, usa el comando kms keys versions create:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --external-key-uri EXTERNAL_KEY_URI

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.
  • EXTERNAL_KEY_URI: Es el URI de la clave de la versión de clave externa nueva.