Inhabilitar y habilitar 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 object DisableCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for disabling the crypto key Version.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}/cryptoKeyVersions/{versionId}";
          // Get crypto key version.
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .CryptoKeyVersionsResource.GetRequest(cloudKms, parent);
          var result = request.Execute();
          result.State = "DISABLED";
          var patchRequest = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .CryptoKeyVersionsResource.PatchRequest(cloudKms, result, parent);
          patchRequest.UpdateMask = "state";
          var patchResult = patchRequest.Execute();
          Console.Write($"Disabled Crypto Key Version: {patchResult.Name}");
          return 0;
      }

Go

func disableCryptoKeyVersion(project, keyRing, key, version string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeyVersions/%s",
		project, location, keyRing, version)

	_, err = client.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions.Patch(
		parent, &cloudkms.CryptoKeyVersion{
			State: "DISABLED",
		}).UpdateMask("state").Do()
	if err != nil {
		return err
	}
	log.Print("Disabled crypto key version.")

	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.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the cryptoKey version
  String cryptoKeyVersion = String.format(
      "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/%s",
      projectId, locationId, keyRingId, cryptoKeyId, version);

  CryptoKeyVersion newVersionState = new CryptoKeyVersion()
      .setState("DISABLED");

  CryptoKeyVersion response = kms.projects().locations().keyRings().cryptoKeys()
      .cryptoKeyVersions()
      .patch(cryptoKeyVersion, newVersionState)
      .setUpdateMask("state")
      .execute();

  System.out.println(response);
  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});
  cryptoKeyVersion.state = 'DISABLED';

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

PHP

/**
 * Disable a CryptoKey version.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param int $version
 * @param string $locationId [optional]
 * @return null
 */
function disable_cryptokey_version($projectId, $keyRingId, $cryptoKeyId, $version, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the KeyRing associated with the CryptoKey.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId,
        $version
    );

    // Disable the CryptoKey version.
    $cryptoKeyVersion = $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions
        ->get($parent);
    $cryptoKeyVersion->setState('DISABLED');

    $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions->patch(
        $parent,
        $cryptoKeyVersion,
        ['updateMask' => 'state']
    );

    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."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # Construct the resource name of the CryptoKeyVersion.
    name = (
        'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}/'
        'cryptoKeyVersions/{}'
        .format(
            project_id, location_id, key_ring_id, crypto_key_id, version_id))

    # Use the KMS API to disable the CryptoKeyVersion.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.cryptoKeyVersions().patch(
        name=name, body={'state': 'DISABLED'}, updateMask='state')
    response = request.execute()

    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/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the crypto key version
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}/cryptoKeys/#{crypto_key_id}/" +
           "cryptoKeyVersions/#{version_id}"

# Get a crypto key version
crypto_key_version = kms_client.get_project_location_key_ring_crypto_key_crypto_key_version resource

# Set the primary version state as disabled for update
crypto_key_version.state = "DISABLED"

# Disable the crypto key version
kms_client.patch_project_location_key_ring_crypto_key_crypto_key_version(
  resource,
  crypto_key_version, update_mask: "state"
)

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 object EnableCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for enabling the crypto key Version.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}/cryptoKeyVersions/{versionId}";
          // Get crypto key version.
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
          .CryptoKeyVersionsResource.GetRequest(cloudKms, parent);
          var result = request.Execute();
          result.State = "ENABLED";
          var patchRequest = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .CryptoKeyVersionsResource.PatchRequest(cloudKms, result, parent);
          patchRequest.UpdateMask = "state";
          var patchResult = patchRequest.Execute();
          Console.Write($"Enabled Crypto Key Version: {patchResult.Name}");
          return 0;
      }

Go

func enableCryptoKeyVersion(project, keyRing, key, version string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeyVersions/%s",
		project, location, keyRing, version)

	_, err = client.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions.Patch(
		parent, &cloudkms.CryptoKeyVersion{
			State: "ENABLED",
		}).UpdateMask("state").Do()
	if err != nil {
		return err
	}
	log.Print("Enabled crypto key version.")

	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.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the cryptoKey version
  String cryptoKeyVersion = String.format(
      "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/%s",
      projectId, locationId, keyRingId, cryptoKeyId, version);

  CryptoKeyVersion newVersionState = new CryptoKeyVersion()
      .setState("ENABLED");

  CryptoKeyVersion response = kms.projects().locations().keyRings().cryptoKeys()
      .cryptoKeyVersions()
      .patch(cryptoKeyVersion, newVersionState)
      .setUpdateMask("state")
      .execute();

  System.out.println(response);
  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});
  cryptoKeyVersion.state = 'ENABLED';

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

PHP

/**
 * Enable a CryptoKey version.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param int $version
 * @param string $locationId [optional]
 * @return null
 */
function enable_cryptokey_version($projectId, $keyRingId, $cryptoKeyId, $version, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the KeyRing associated with the CryptoKey.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId,
        $version
    );

    // Enable the CryptoKey version.
    $cryptoKeyVersion = $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions
        ->get($parent);
    $cryptoKeyVersion->setState('ENABLED');

    $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions->patch(
        $parent,
        $cryptoKeyVersion,
        ['updateMask' => 'state']
    );

    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."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # Construct the resource name of the CryptoKeyVersion.
    name = (
        'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}/'
        'cryptoKeyVersions/{}'
        .format(
            project_id, location_id, key_ring_id, crypto_key_id, version_id))

    # Use the KMS API to enable the CryptoKeyVersion.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.cryptoKeyVersions().patch(
        name=name, body={'state': 'ENABLED'}, updateMask='state')
    response = request.execute()

    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/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the crypto key version
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}/cryptoKeys/#{crypto_key_id}/" +
           "cryptoKeyVersions/#{version_id}"

# Get a version of the crypto key
crypto_key_version = kms_client.get_project_location_key_ring_crypto_key_crypto_key_version resource

# Set the primary version state as disabled for update
crypto_key_version.state = "ENABLED"

# Enable the crypto key version
kms_client.patch_project_location_key_ring_crypto_key_crypto_key_version(
  resource,
  crypto_key_version, update_mask: "state"
)

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 sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

Documentación de Cloud KMS