Fazer rotação de uma chave

Nesta página, mostramos como fazer a rotação automática ou manual de uma chave. Para mais informações sobre a rotação de chaves em geral, consulte Rotação de chaves.

Funções exigidas

Para ter as permissões necessárias para alternar as chaves, peça ao administrador para conceder a você os seguintes papéis do IAM na sua chave:

Para mais informações sobre como conceder papéis, consulte Gerenciar acesso.

Esses papéis predefinidos têm as permissões necessárias para alternar as chaves. Para conferir as permissões exatas necessárias, expanda a seção Permissões necessárias:

Permissões necessárias

As seguintes permissões são necessárias para alternar as chaves:

  • Alterar versão da chave primária: cloudkms.cryptoKeys.update
  • Mudar ou desativar o giro automático: cloudkms.cryptoKeys.update
  • Crie uma nova versão da chave: cloudkms.cryptoKeyVersions.create
  • Desative versões de chave antigas: cloudkms.cryptoKeyVersions.update
  • Recriptografar dados:
    • cloudkms.cryptoKeyVersions.useToDecrypt
    • cloudkms.cryptoKeyVersions.useToEncrypt

Essas permissões também podem ser concedidas com funções personalizadas ou outros papéis predefinidos.

Um único usuário com uma função personalizada que contém todas essas permissões pode rotacionam chaves e recriptografam dados por conta própria. Usuários com o papel de Administrador do Cloud KMS e o papel criptografador/descriptografador de CryptoKey do Cloud KMS podem trabalhar juntos e recriptografar dados. Siga o princípio do privilégio mínimo ao atribuir papéis de segurança na nuvem. Para mais detalhes, consulte Permissões e papéis.

Quando você faz a rotação de uma chave, os dados criptografados com versões anteriores não são automaticamente recriptografados. Para saber mais, consulte descriptografar e recriptografar. Fazer a rotação de uma chave não desativa ou destrói automaticamente nenhuma versão de chave atual.

Configurar a rotação automática

Para configurar a rotação automática ao criar uma nova chave:

Console

Quando você usa o console do Google Cloud para criar uma chave, o Cloud KMS define período de rotação e o tempo da próxima rotação automaticamente. Você pode optar por usar os valores padrão ou especificar valores diferentes.

Para especificar um período de rotação e um horário de início diferentes, ao criar a chave, mas antes de clicar o botão Criar:

  1. Em Período de rotação de chaves, selecione uma opção.

  2. Em A partir de, selecione a data em que as primeiras campanhas que a rotação aconteça. Você pode deixar A partir de com o valor padrão como inicie a primeira rotação automática um período de rotação de chaves a partir de quando você para criar a chave.

gcloud

Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da 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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • ROTATION_PERIOD: o intervalo fazer a rotação da chave, por exemplo, 30d para fazer a rotação a cada 30 dias. A rotação deve ser de no mínimo 1 dia e no máximo 100 anos. Para mais informações, consulte CryptoKey.rotationPeriod (link em inglês).
  • NEXT_ROTATION_TIME: o carimbo de data/hora em que a conclusão é concluída. a primeira rotação, por exemplo, "2023-01-01T01:02:03". É possível omitir --next-rotation-time para programar a primeira rotação para sete dias a partir da execução do kubectl. Para mais informações, consulte CryptoKey.nextRotationTime.

Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help.

C#

Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.


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

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

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

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

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

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

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

        // Return the result.
        return result;
    }
}

Go

Para executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.

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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.

//
// 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 executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.

# 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

Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.

Para criar uma chave, use o 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"}'

Substitua:

  • PURPOSE: o propósito da chave.
  • ROTATION_PERIOD: o intervalo fazer a rotação da chave, por exemplo, 30d para fazer a rotação a cada 30 dias. A rotação deve ser de no mínimo 1 dia e no máximo 100 anos. Para mais informações, consulte CryptoKey.rotationPeriod (link em inglês).
  • NEXT_ROTATION_TIME: o carimbo de data/hora em que a conclusão é concluída. a primeira rotação, por exemplo, "2023-01-01T01:02:03". É possível omitir --next-rotation-time para programar a primeira rotação para sete dias a partir da execução do kubectl. Para mais informações, consulte CryptoKey.nextRotationTime.

Para configurar a rotação automática em uma chave atual:

Console

  1. Acesse a página Gerenciamento de chaves no console do Google Cloud.

    Acessar a página "Gerenciamento de chaves"

  2. Clique no nome do keyring que contém a chave. adicionar uma programação de rotação.

  3. Clique na chave em que você quer adicionar uma programação de rotação.

  4. No cabeçalho, clique em Editar período de rotação.

  5. No prompt, escolha novos valores para os campos Período de rotação e A partir de.

  6. No prompt, clique em Salvar.

gcloud

Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da Google Cloud CLI.

gcloud kms keys update KEY_NAME \
    --location LOCATION \
    --keyring KEY_RING \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_ROTATION_TIME

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • ROTATION_PERIOD: o intervalo fazer a rotação da chave, por exemplo, 30d para fazer a rotação a cada 30 dias. A rotação deve ser de no mínimo 1 dia e no máximo 100 anos. Para mais informações, consulte CryptoKey.rotationPeriod (link em inglês).
  • NEXT_ROTATION_TIME: o carimbo de data/hora em que a conclusão é concluída. a primeira rotação, por exemplo, "2023-01-01T01:02:03". É possível omitir --next-rotation-time para programar a primeira rotação para sete dias a partir da execução do kubectl. Para mais informações, consulte CryptoKey.nextRotationTime.

Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help.

C#

Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.


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 executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.

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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.

//
// 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 executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.

# 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

Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.

Para atualizar uma chave, use 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"}'

Substitua:

  • ROTATION_PERIOD: o intervalo fazer a rotação da chave, por exemplo, 30d para fazer a rotação a cada 30 dias. A rotação deve ser de no mínimo 1 dia e no máximo 100 anos. Para mais informações, consulte CryptoKey.rotationPeriod (link em inglês).
  • NEXT_ROTATION_TIME: o carimbo de data/hora em que a conclusão é concluída. a primeira rotação, por exemplo, "2023-01-01T01:02:03". É possível omitir --next-rotation-time para programar a primeira rotação para sete dias a partir da execução do kubectl. Para mais informações, consulte CryptoKey.nextRotationTime.

Fazer a rotação manual de uma chave

Primeiro, crie uma nova versão da chave:

Console

  1. Acesse a página Gerenciamento de chaves no console do Google Cloud.

    Acessar a página "Gerenciamento de chaves"

  2. Clique no nome do keyring que contém a chave para a qual você criará uma nova versão da chave.

  3. Clique na chave para a qual você criará uma nova versão da chave.

  4. No cabeçalho, clique em Girar.

  5. Na solicitação, clique em Girar para confirmar.

gcloud

Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da Google Cloud CLI.

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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.

As versões de chave são numeradas sequencialmente.

Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help.

C#

Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.


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 executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.

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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.

//
// 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 executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.

# 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

Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.

Para fazer a rotação manual de uma chave, primeiro crie uma nova versão de chave chamando o 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"

Esse comando cria uma nova versão de chave, mas não a define como a versão primária.

Para definir uma nova versão de chave como primária, consulte Como definir uma versão existente como a versão da chave primária.

Se necessário, recriptografe os dados que foram criptografados usando a versão anterior da chave.

Definir uma versão atual como a chave primária

Para definir uma versão de chave diferente como a versão principal de uma chave, atualize a chave com as informações da nova versão principal. Uma versão de chave precisa estar ativada para que você possa configurá-la como a versão principal.

Console

  1. Acesse a página Gerenciamento de chaves no console do Google Cloud.

    Acessar a página "Gerenciamento de chaves"

  2. Clique no nome do keyring que contém a chave cuja versão principal você quer atualizar.

  3. Clique na chave cuja versão principal você quer atualizar.

  4. Na linha correspondente à versão da chave que você quer tornar principal, clique em Ver mais .

  5. Clique em Tornar versão principal no menu.

  6. No prompt de confirmação, clique em Tornar principal.

gcloud

Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da Google Cloud CLI.

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --primary-version KEY_VERSION

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • KEY_VERSION: o número da nova versão da chave primária.

Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help.

C#

Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.


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 executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.

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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.

//
// 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 executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.

# 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 executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.

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

Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.

Altere a versão da chave primária chamando 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"}'

Substitua:

  • PROJECT_ID: o ID do projeto que contém o keyring.
  • LOCATION: o local do keyring no Cloud KMS.
  • KEY_RING: o nome do keyring que contém a chave.
  • KEY_NAME: o nome da chave;
  • KEY_VERSION: o número da nova versão da chave primária.

Quando você altera a versão da chave primária, a mudança normalmente se torna consistente em 1 minuto. No entanto, essa alteração pode levar até 3 horas para ser propagada em em casos excepcionais. Durante esse período, a versão principal anterior pode ser usada para e criptografar os dados. Para saber mais, consulte Consistência de recursos do Cloud KMS.

Desativar rotação automática

Para fazer isso, limpe a programação de rotação da chave:

Console

  1. Acesse a página Gerenciamento de chaves no console do Google Cloud.

    Acessar a página "Gerenciamento de chaves"

  2. Clique no nome do keyring que contém a chave. remova a programação de rotação.

  3. Clique na chave da qual você quer remover a programação de rotação.

  4. No cabeçalho, clique em Editar período de rotação.

  5. No prompt, clique no campo Período de rotação e selecione Nunca (rotação manual).

  6. No prompt, clique em Salvar.

gcloud

Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da Google Cloud CLI.

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --remove-rotation-schedule

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.

Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help.

C#

Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.


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 executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.

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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.

//
// 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 executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.

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 executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.

# 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 executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.

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

Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.

Para atualizar uma chave, use 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 acessar mais detalhes sobre rotationPeriod e nextRotationTime, consulte keyRings.cryptoKeys.

Girar uma chave externa

Fazer a rotação de uma chave externa coordenada

É possível configurar a rotação automática para coordenadas simétricas chaves externas. Também é possível criar manualmente uma nova versão de chave para versões chaves externas coordenadas assimétricas.

A rotação ou a criação de uma nova versão de chave faz com que todos os dados recém-criados sejam protegidos com essa chave sejam criptografados com a nova versão. Dados protegidos com uma versão anterior de chave não será recriptografada. Por isso, sua chave externa de chave deve continuar fazendo o material da chave da versão anterior disponíveis para uso.

Para criar uma nova versão para uma chave externa coordenada, siga estas etapas:

Console

  1. No console do Google Cloud, acesse Gerenciamento de chaves.

    Vá para Gerenciamento de chaves

  2. Selecione o keyring e a chave.

  3. Clique em Criar versão. Uma mensagem indica que a nova versão da chave serão gerados no Cloud KMS e no EKM. Se aparecer um Caminho da chave ou URI da chave, a chave selecionada não é um campo coordenado chave externa.

  4. Para confirmar que você quer criar uma nova versão da chave, clique em Criar versão.

A nova versão da chave aparece no estado Geração pendente. Para simétrico , as versões de chaves criadas manualmente não são definidas automaticamente como versão da chave primária. É possível definir a nova versão da chave como principal.

CLI da gcloud

Para criar uma nova versão de chave simétrica e defini-la como a versão da chave primária, Use o comando kms keys versions create com a sinalização --primary:

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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.

Para criar uma nova versão de chave assimétrica ou criar uma nova chave simétrica que não seja a versão da chave primária, use o comando kms keys versions create:

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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.

Alternar um Cloud EKM gerenciado manualmente usando uma chave VPC

Primeiro, gire o material da chave externa no gerenciador externo. Se isso resultar em um novo caminho de chave, será preciso alternar ou criar um novo Cloud EKM versão da chave com o novo caminho. Para chaves de criptografia simétrica, rota a Chave do Cloud EKM e especifique o novo caminho da chave externa de projeto. Para chaves assimétricas, crie uma nova versão da chave e especifique uma nova. caminho.

A rotação ou a criação de uma nova versão de chave faz com que todos os dados recém-criados sejam protegidos com essa chave sejam criptografados com a nova versão. Dados protegidos com uma versão anterior de chave não será recriptografada. Por isso, sua chave externa de chave deve continuar fazendo o material da chave da versão anterior disponíveis para uso.

Se o material da chave no sistema do parceiro de gerenciamento de chaves externas não mudar, mas a chave alterações de caminho, atualize o arquivo caminho sem girar a chave.

Console

  1. No console do Google Cloud, acesse Gerenciamento de chaves.

    Vá para Gerenciamento de chaves

  2. Selecione o keyring e a chave.

  3. Clique em Alternar chave.

  4. Em Caminho da chave, insira o caminho da chave da nova versão.

  5. Clique em Alternar chave para confirmar.

gcloud

Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da Google Cloud CLI.

Para criar uma nova versão de chave simétrica e defini-la como a versão da chave primária, Use o comando kms keys versions create com a sinalização --primary:

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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • EXTERNAL_KEY_PATH: o caminho para o novo arquivo externo. a versão da chave.

Para criar uma nova versão de chave assimétrica ou criar uma nova chave simétrica que não seja a versão da chave primária, use o 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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • EXTERNAL_KEY_PATH: o caminho para o novo arquivo externo. a versão da chave.

Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help.

Depois que a versão da chave for criada, você poderá usá-la como faria use qualquer outra versão da chave do Cloud KMS.

Alternar um Cloud EKM gerenciado manualmente usando uma chave de Internet

Primeiro, gire o material da chave externa no gerenciador externo. Se isso resultar em um novo URI, será preciso girar ou criar uma nova chave do Cloud EKM com o novo URI. Para chaves de criptografia simétrica, rota a chave do Cloud EKM e especifique o novo URI da chave externa de projeto. Para chaves assimétricas, crie uma nova versão da chave e especifique uma nova. URI.

A rotação ou a criação de uma nova versão de chave faz com que todos os dados recém-criados sejam protegidos com essa chave sejam criptografados com a nova versão. Dados protegidos com uma versão anterior de chave não será recriptografada. Por isso, sua chave externa de chave deve continuar fazendo o material da chave da versão anterior disponíveis para uso.

Se o material da chave no sistema do parceiro de gerenciamento de chaves externas não mudar, mas o URI é possível atualizar o namespace externo da chave URI sem girar a chave.

Console

  1. No console do Google Cloud, acesse Gerenciamento de chaves.

    Vá para Gerenciamento de chaves

  2. Selecione o keyring e a chave.

  3. Selecione Alternar chave para chaves simétricas ou Criar versão para chaves assimétricas.

  4. Insira o URI da nova chave e selecione Alternar chave para chaves simétricas ou Crie uma versão para chaves assimétricas.

A nova versão da chave se torna a principal.

CLI da gcloud

Para criar uma nova versão de chave simétrica e defini-la como a versão da chave primária, Use o comando kms keys versions create com a sinalização --primary:

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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • EXTERNAL_KEY_URI: o URI da chave do novo objeto externo. a versão da chave.

Para criar uma nova versão de chave assimétrica ou criar uma nova chave simétrica que não seja a versão da chave primária, use o comando kms keys versions create:

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

Substitua:

  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • EXTERNAL_KEY_URI: o URI da chave do novo objeto externo. a versão da chave.