Enabling and disabling key versions

A key version has a state which determines if it can be used for encryption and decryption.

To enable or disable a key version, a user needs the appropriate Cloud Identity and Access Management role or permission.

  • The pre-defined roles roles/cloudkms.admin, roles/owner, or roles/editor can enable or disable a key version.

  • A custom role that contains the cloudkms.cryptoKeyVersions.update permission can enable or disable a key version.

Disable an enabled key version

Only a key version which is enabled can be disabled. This is done with the method UpdateCryptoKeyVersion using the state field, client library methods that map to UpdateCryptoKeyVersion, gcloud kms keys versions disable, or the Google Cloud Platform Console.

Console

  1. Go to the Cryptographic Keys page in the GCP Console.
    Go to the Cryptographic Keys page

  2. Click the name of the key ring that contains the key whose key version you will disable.

  3. Click the key whose key version you want to disable.

  4. Click the key version that you want to disable.

  5. Click Disable.

  6. When prompted to confirm the disabling of the key version, click Disable.

Command-line

To disable version 42 of key answer in key ring answers in the global location.

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

Enable a disabled key version

Only a key version which is disabled can be enabled. This is done with the method UpdateCryptoKeyVersion using the state field, client library methods that map to UpdateCryptoKeyVersion, gcloud kms keys versions enable, or the Google Cloud Platform Console.

Once you enable a key, it is instantly available for encrypting and decrypting data.

Console

  1. Go to the Cryptographic Keys page in the GCP Console.
    Go to the Cryptographic Keys page

  2. Click the name of the key ring that contains the key whose key version you will enable.

  3. Click the key whose key version you want to enable.

  4. Click the key version that you want to enable.

  5. Click Enable.

  6. When prompted to confirm the enabling of the key version, click Enable.

Command-line

To enable version 42 of key answer in key ring answers in the global location.

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

Consistency when enabling and disabling a key version

Enabling a key version is a strongly consistent operation. The enabled key version is instantly available for encrypting and decrypting data. Disabling a key version is an eventually consistent operation. The disabled key version is still usable for encrypting and decrypting data, on average for about 40 minutes, and up to 3 hours. For more details about consistency of key versions, see Cloud KMS resource consistency.

Was this page helpful? Let us know how we did:

Send feedback about...