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

// Your Google Cloud Platform project ID
// const projectId = 'YOUR_PROJECT_ID';

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

// The name of the crypto key version's key ring, e.g. "my-key-ring"
// const keyRingId = 'my-key-ring';

// The name of the version's crypto key, e.g. "my-key"
// const cryptoKeyId = 'my-key';

// The version's id, e.g. 123
// const version = 123;

// Builds and authorizes a Cloud KMS client
buildAndAuthorizeService((err, cloudkms) => {
  if (err) {
    console.log(err);
    return;
  }

  let request = {
    // This will be a path parameter in the request URL
    name: `projects/${projectId}/locations/${locationId}/keyRings/${keyRingId}/cryptoKeys/${cryptoKeyId}/cryptoKeyVersions/${version}`
  };

  // Gets a crypto key version
  cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.get(request, (err, getResponse) => {
    if (err) {
      console.log(err);
      return;
    }

    const cryptoKeyVersion = getResponse.data;
    cryptoKeyVersion.state = 'DISABLED';

    request = {
      // This will be a path parameter in the request URL
      name: request.name,
      // This will be a query parameter in the request URL
      updateMask: 'state',
      // This will be the request body
      resource: cryptoKeyVersion
    };

    // Disables a crypto key version
    cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.patch(request, (err, patchResponse) => {
      if (err) {
        console.log(err);
        return;
      }

      console.log(`Crypto key version ${patchResponse.data.name} disabled.`);
    });
  });
});

function buildAndAuthorizeService (callback) {
  // Imports the Google APIs client library
  const {google} = require('googleapis');

  // Acquires credentials
  google.auth.getApplicationDefault((err, authClient) => {
    if (err) {
      callback(err);
      return;
    }

    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
      authClient = authClient.createScoped([
        'https://www.googleapis.com/auth/cloud-platform'
      ]);
    }

    // Instantiates an authorized client
    const cloudkms = google.cloudkms({
      version: 'v1',
      auth: authClient
    });

    callback(null, cloudkms);
  });
}

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

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

// Your Google Cloud Platform project ID
// const projectId = 'YOUR_PROJECT_ID';

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

// The name of the crypto key version's key ring, e.g. "my-key-ring"
// const keyRingId = 'my-key-ring';

// The name of the version's crypto key, e.g. "my-key"
// const cryptoKeyId = 'my-key';

// The version's id, e.g. 123
// const version = 123;

// Builds and authorizes a Cloud KMS client
buildAndAuthorizeService((err, cloudkms) => {
  if (err) {
    console.log(err);
    return;
  }

  let request = {
    // This will be a path parameter in the request URL
    name: `projects/${projectId}/locations/${locationId}/keyRings/${keyRingId}/cryptoKeys/${cryptoKeyId}/cryptoKeyVersions/${version}`
  };

  // Gets a crypto key version
  cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.get(request, (err, getResponse) => {
    if (err) {
      console.log(err);
      return;
    }

    const cryptoKeyVersion = getResponse.data;
    cryptoKeyVersion.state = 'ENABLED';

    request = {
      // This will be a path parameter in the request URL
      name: request.name,
      // This will be a query parameter in the request URL
      updateMask: 'state',
      // This will be the request body
      resource: cryptoKeyVersion
    };

    // Enables a crypto key version
    cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.patch(request, (err, patchResponse) => {
      if (err) {
        console.log(err);
        return;
      }

      console.log(`Crypto key version ${patchResponse.data.name} enabled.`);
    });
  });
});

function buildAndAuthorizeService (callback) {
  // Imports the Google APIs client library
  const {google} = require('googleapis');

  // Acquires credentials
  google.auth.getApplicationDefault((err, authClient) => {
    if (err) {
      callback(err);
      return;
    }

    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
      authClient = authClient.createScoped([
        'https://www.googleapis.com/auth/cloud-platform'
      ]);
    }

    // Instantiates an authorized client
    const cloudkms = google.cloudkms({
      version: 'v1',
      auth: authClient
    });

    callback(null, cloudkms);
  });
}

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

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

Cloud KMS Documentation