Inhabilita y habilita versiones de clave

Una versión de clave tiene un estado que determina si se puede usar para encriptación o desencriptación.

Para habilitar o inhabilitar una versión de clave, es necesario que un usuario tenga la función o el permiso adecuado de Cloud Identity and Access Management.

  • Las funciones predefinidas roles/cloudkms.admin, roles/owner o roles/editor pueden habilitar o inhabilitar una versión de clave.

  • Una función personalizada que contenga el permiso cloudkms.cryptoKeyVersions.update puede habilitar o inhabilitar una versión de clave.

Inhabilita una versión de clave habilitada

Solo se pueden inhabilitar las claves habilitadas. Esta acción se realiza con el método UpdateCryptoKeyVersion mediante el campo state, los métodos de biblioteca cliente que se asignan a UpdateCryptoKeyVersion, gcloud kms keys versions disable, o Google Cloud Platform Console.

Console

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

  2. Haz clic en el nombre del llavero de claves que contiene la clave cuya versión de clave se inhabilitará.

  3. Haz clic en la clave cuya versión de clave deseas inhabilitar.

  4. Haz clic en la versión de clave que deseas inhabilitar.

  5. Haz clic en Inhabilitar.

  6. Cuando se te solicite confirmar la inhabilitación de la versión de clave, haz clic en Inhabilitar.

Línea de comandos

Para inhabilitar la versión 42 de la clave answer del llavero de claves answers en la ubicación global, usa este comando:

gcloud kms keys versions disable 42 --location global \
  --keyring answers --key answer

C#

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

          // The CryptoKeyVersion to disable.
          CryptoKeyVersionName versionName =
              new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId);

          CryptoKeyVersion version = client.GetCryptoKeyVersion(versionName);
          version.State = CryptoKeyVersion.Types.CryptoKeyVersionState.Disabled;

          FieldMask fieldMask = new FieldMask { Paths = { "state" } };

          CryptoKeyVersion patchResult = client.UpdateCryptoKeyVersion(version, fieldMask);

          Console.Write($"Disabled Crypto Key Version: {patchResult.Name}");
      }

Go


// disableCryptoKeyVersion disables a specified key version on KMS.
// example keyVersionName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
func disableCryptoKeyVersion(w io.Writer, keyVersionName string) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return err
	}
	// Build the request.
	req := &kmspb.UpdateCryptoKeyVersionRequest{
		CryptoKeyVersion: &kmspb.CryptoKeyVersion{
			Name:  keyVersionName,
			State: kmspb.CryptoKeyVersion_DISABLED,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"state"},
		},
	}
	// Call the API.
	result, err := client.UpdateCryptoKeyVersion(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Disabled crypto key version: %s", result)
	return nil
}

Java


/**
 * Disables the given version of the crypto key.
 */
public static CryptoKeyVersion disableCryptoKeyVersion(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
    throws IOException {
  // Create the Cloud KMS client.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey version
    String versionName = CryptoKeyVersionName.format(
        projectId, locationId, keyRingId, cryptoKeyId, version);

    // Retrieve the current state
    CryptoKeyVersion current = client.getCryptoKeyVersion(versionName);

    // Build a copy that updates the state to disabled
    CryptoKeyVersion updated = CryptoKeyVersion.newBuilder()
        .setName(current.getName())
        .setState(CryptoKeyVersionState.DISABLED)
        .build();

    // Create a FieldMask that only allows 'state' to be updated
    FieldMask fieldMask = FieldMaskUtil.fromString(CryptoKeyVersion.class, "state");

    // Update the version state
    CryptoKeyVersion response = client.updateCryptoKeyVersion(updated, fieldMask);

    return response;
  }
}

Node.js

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

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

  // Get the full path to the crypto key
  const name = client.cryptoKeyVersionPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId,
    version
  );

  // Gets a crypto key version
  const [cryptoKeyVersion] = await client.getCryptoKeyVersion({name});

  // Disables a crypto key version
  const [result] = await client.updateCryptoKeyVersion({
    cryptoKeyVersion: {state: 'DISABLED', name: cryptoKeyVersion.name},
    updateMask: ['state'],
  });
  console.log(`Crypto key version ${result.name} disabled.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionState;
use Google\Protobuf\FieldMask;

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

$kms = new KeyManagementServiceClient();

// The resource name of the Crypto Key version.
$cryptoKeyVersionName = $kms->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $cryptoKeyId, $version);

// Get the CryptoKey.
$cryptoKeyVersion = $kms->getCryptoKeyVersion($cryptoKeyVersionName);
// Disable the cryptokey
$cryptoKeyVersion->setState(CryptoKeyVersionState::DISABLED);

$updateMask = new FieldMask();
$updateMask->setPaths(['state']);
$kms->updateCryptoKeyVersion($cryptoKeyVersion, $updateMask);

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

Python

def disable_crypto_key_version(project_id, location_id, key_ring_id,
                               crypto_key_id, version_id):
    """Disables a CryptoKeyVersion associated with a given CryptoKey and
    KeyRing."""

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

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

    # Construct the resource name of the CryptoKeyVersion.
    name = client.crypto_key_version_path(project_id, location_id, key_ring_id,
                                          crypto_key_id, version_id)

    # Use the KMS API to disable the CryptoKeyVersion.
    new_state = enums.CryptoKeyVersion.CryptoKeyVersionState.DISABLED
    version = {'name': name, 'state': new_state}
    update_mask = {'paths': ["state"]}

    # Print results
    response = client.update_crypto_key_version(version, update_mask)
    print('CryptoKeyVersion {}\'s state has been set to {}.'.format(
        name, response.state))

Ruby

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

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

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

# Retrieve the crypto key version to update
version_path = CloudKMS::KeyManagementServiceClient.crypto_key_version_path(
  project_id, location_id, key_ring_id, crypto_key_id, version_id
)
version = client.get_crypto_key_version version_path

# Set the version state to disabled for update
version.state = CloudKMS::CryptoKeyVersion::CryptoKeyVersionState::DISABLED
update_mask = Google::Protobuf::FieldMask.new
update_mask.paths << "state"

# Disable the crypto key version
result = client.update_crypto_key_version version, update_mask

puts "Disabled version #{version_id} of #{crypto_key_id}"

Habilita una versión de clave inhabilitada

Solo se pueden habilitar las claves inhabilitadas. Esta acción se realiza con el método UpdateCryptoKeyVersion mediante el campo state, los métodos de biblioteca cliente que se asignan a UpdateCryptoKeyVersion, gcloud kms keys versions enable, o Google Cloud Platform Console.

Cuando la habilitas, la versión de clave está disponible inmediatamente para la encriptación y desencriptación de datos.

Console

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

  2. Haz clic en el nombre del llavero de claves que contiene la clave cuya versión de clave se habilitará.

  3. Haz clic en la clave cuya versión de clave deseas habilitar.

  4. Haz clic en la versión de clave que deseas habilitar.

  5. Haz clic en Habilitar.

  6. Cuando se te solicite confirmar la habilitación de la versión de clave, haz clic en Habilitar.

Línea de comandos

Para habilitar la versión 42 de la clave answer del llavero de claves answers en la ubicación global, usa este comando:

gcloud kms keys versions enable 42 --location global \
  --keyring answers --key answer

C#

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

          // The CryptoKeyVersion to enable.
          CryptoKeyVersionName versionName =
              new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId);

          CryptoKeyVersion version = client.GetCryptoKeyVersion(versionName);
          version.State = CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled;

          FieldMask fieldMask = new FieldMask { Paths = { "state" } };

          CryptoKeyVersion patchResult = client.UpdateCryptoKeyVersion(version, fieldMask);
          Console.Write($"Enabled Crypto Key Version: {patchResult.Name}");
      }

Go


// enableCryptoKeyVersion enables a previously disabled key version on KMS.
// example keyVersionName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
func enableCryptoKeyVersion(w io.Writer, keyVersionName string) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return err
	}
	// Build the request.
	req := &kmspb.UpdateCryptoKeyVersionRequest{
		CryptoKeyVersion: &kmspb.CryptoKeyVersion{
			Name:  keyVersionName,
			State: kmspb.CryptoKeyVersion_ENABLED,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"state"},
		},
	}
	// Call the API.
	result, err := client.UpdateCryptoKeyVersion(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Enabled crypto key version: %s", result)
	return nil
}

Java

/**
 * Enables the given version of the crypto key.
 */
public static CryptoKeyVersion enableCryptoKeyVersion(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
    throws IOException {

  // Create the Cloud KMS client.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey version
    String versionName = CryptoKeyVersionName.format(
        projectId, locationId, keyRingId, cryptoKeyId, version);

    // Retrieve the current state
    CryptoKeyVersion current = client.getCryptoKeyVersion(versionName);

    // Build a copy that updates the state to enabled
    CryptoKeyVersion updated = CryptoKeyVersion.newBuilder()
        .setName(current.getName())
        .setState(CryptoKeyVersionState.ENABLED)
        .build();

    // Create a FieldMask that only allows 'state' to be updated
    FieldMask fieldMask = FieldMaskUtil.fromString(CryptoKeyVersion.class, "state");

    // Update the version state
    CryptoKeyVersion response = client.updateCryptoKeyVersion(updated, fieldMask);

    return response;
  }
}

Node.js

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

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

  // Get the full path to the crypto key
  const name = client.cryptoKeyVersionPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId,
    version
  );

  // Gets a crypto key version
  const [cryptoKeyVersion] = await client.getCryptoKeyVersion({name});

  // enables a crypto key version
  const [result] = await client.updateCryptoKeyVersion({
    cryptoKeyVersion: {state: 'ENABLED', name: cryptoKeyVersion.name},
    updateMask: ['state'],
  });
  console.log(`Crypto key version ${result.name} enabled.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionState;
use Google\Protobuf\FieldMask;

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

$kms = new KeyManagementServiceClient();

// The resource name of the Crypto Key version.
$cryptoKeyVersionName = $kms->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $cryptoKeyId, $version);

// Get the CryptoKey.
$cryptoKeyVersion = $kms->getCryptoKeyVersion($cryptoKeyVersionName);
// Enable the cryptokey
$cryptoKeyVersion->setState(CryptoKeyVersionState::ENABLED);

$updateMask = new FieldMask();
$updateMask->setPaths(['state']);
$kms->updateCryptoKeyVersion($cryptoKeyVersion, $updateMask);

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

Python

def enable_crypto_key_version(project_id, location_id, key_ring_id,
                              crypto_key_id, version_id):
    """Enables a CryptoKeyVersion associated with a given CryptoKey and
    KeyRing."""

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

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

    # Construct the resource name of the CryptoKeyVersion.
    name = client.crypto_key_version_path(project_id, location_id, key_ring_id,
                                          crypto_key_id, version_id)

    # Use the KMS API to enable the CryptoKeyVersion.
    new_state = enums.CryptoKeyVersion.CryptoKeyVersionState.ENABLED
    version = {'name': name, 'state': new_state}
    update_mask = {'paths': ["state"]}

    # Print results
    response = client.update_crypto_key_version(version, update_mask)
    print('CryptoKeyVersion {}\'s state has been set to {}.'.format(
        name, response.state))

Ruby

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

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

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

# Retrieve the crypto key version to update
version_path = CloudKMS::KeyManagementServiceClient.crypto_key_version_path(
  project_id, location_id, key_ring_id, crypto_key_id, version_id
)
version = client.get_crypto_key_version version_path

# Set the version state to enabled for update
version.state = CloudKMS::CryptoKeyVersion::CryptoKeyVersionState::ENABLED
update_mask = Google::Protobuf::FieldMask.new
update_mask.paths << "state"

# Enable the crypto key version
result = client.update_crypto_key_version version, update_mask

puts "Enabled version #{version_id} of #{crypto_key_id}"

Coherencia cuando se habilita o inhabilita una versión de clave

Habilitar una versión de clave es una operación de coherencia sólida. La versión de clave habilitada está disponible inmediatamente para la encriptación y desencriptación de datos. Inhabilitar una versión de clave es una operación de coherencia eventual. La versión de clave inhabilitada aún puede usarse para encriptar y desencriptar datos por 40 minutos, en promedio, y hasta por 3 horas. Para obtener más detalles sobre la coherencia de las versiones de clave, consulta Coherencia de recursos de Cloud KMS.

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

Enviar comentarios sobre...