Enabling and disabling key versions

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

A CryptoKeyVersion can move from Enabled to Disabled and from Disabled to Enabled using UpdateCryptoKeyVersion. To do this, a user needs the IAM role roles/cloudkms.admin, roles/owner, or roles/editor.

Disable an enabled CryptoKeyVersion

Only a CryptoKeyVersion which is Enabled can be Disabled. This is done with the method UpdateCryptoKeyVersion, changing the state field.

Command-line

To disable version "42" of CryptoKey "answer" in KeyRing "answers"

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

C#

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

      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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

// 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, cryptoKeyVersion) => {
    if (err) {
      console.log(err);
      return;
    }

    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, cryptoKeyVersion) => {
      if (err) {
        console.log(err);
        return;
      }

      console.log(`Crypto key version ${cryptoKeyVersion.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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

Only a CryptoKeyVersion which is Disabled can be Enabled. This is done with the method UpdateCryptoKeyVersion, changing the state field.

Command-line

To enable version "42" of CryptoKey "answer" in KeyRing "answers"

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

C#

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

      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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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
}

Node.js

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

// 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, cryptoKeyVersion) => {
    if (err) {
      console.log(err);
      return;
    }

    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, cryptoKeyVersion) => {
      if (err) {
        console.log(err);
        return;
      }

      console.log(`Crypto key version ${cryptoKeyVersion.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

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

/**
 * 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);
}

Ruby

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud KMS Documentation