Destroying and restoring key versions

A CryptoKeyVersion has a state which determines if its key material exists.

A CryptoKeyVersion which is Enabled or Disabled can move to Scheduled for destruction using DestroyCryptoKeyVersion, and it can be moved from Scheduled for destruction to Disabled using RestoreCryptoKeyVersion. To do this, a user needs the IAM role roles/cloudkms.admin or roles/owner.

Schedule a CryptoKeyVersion for destruction (Destroy a CryptoKeyVersion)

Only CryptoKeyVersions which are Enabled or Disabled can be Scheduled for destruction. This is done with the method DestroyCryptoKeyVersion.

To prevent accidents, and damage from malicious individuals, when DestroyCryptoKeyVersion is used, the key material is NOT immediately Destroyed. Rather, the CryptoKeyVersion moves to Scheduled for destruction for 24 hours, after which it is automatically destroyed. There is no way to override this safety fallback.

Destruction is removal of the key material, but a record of the version still exists (e.g., the version number cannot be reused). This is NOT reversible - any data encrypted with this version will not be recoverable.

Command-line

Destroy version "42" of CryptoKey "answer" in KeyRing "answers"

gcloud kms keys versions destroy 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 DestroyCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for destroying the crypto key Version.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}/cryptoKeyVersions/{versionId}";
          DestroyCryptoKeyVersionRequest destroyRequest = new DestroyCryptoKeyVersionRequest();
          // Destroy crypto key version.
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .CryptoKeyVersionsResource.DestroyRequest(cloudKms, destroyRequest, parent);
          var result = request.Execute();
          Console.Write($"Destroyed Crypto Key Version: {result.Name}");
          return 0;
      }

Go

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

func destroyCryptoKeyVersion(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.Destroy(
		parent, &cloudkms.DestroyCryptoKeyVersionRequest{}).Do()
	if err != nil {
		return err
	}
	log.Print("Destroyed crypto key version.")

	return nil
}

Java

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

/**
 * Marks the given version of a crypto key to be destroyed at a scheduled future point.
 */
public static CryptoKeyVersion destroyCryptoKeyVersion(
    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);

  DestroyCryptoKeyVersionRequest destroyRequest = new DestroyCryptoKeyVersionRequest();

  CryptoKeyVersion destroyed = kms.projects().locations().keyRings().cryptoKeys()
      .cryptoKeyVersions()
      .destroy(cryptoKeyVersion, destroyRequest)
      .execute();

  System.out.println(destroyed);
  return destroyed;
}

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

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

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

    console.log(`Crypto key version ${cryptoKeyVersion.name} destroyed.`);
  });
});

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.

/**
 * Destroy a CryptoKey version.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $version
 * @param string $locationId [optional]
 * @return Google_Service_CloudKMS_CryptoKeyVersion
 */
function destroy_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 CryptoKey version.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId,
        $version
    );

    // Destroy the CryptoKey version.
    $request = new Google_Service_CloudKMS_DestroyCryptoKeyVersionRequest();
    $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions->destroy(
        $parent,
        $request
    );

    printf('Destroyed 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 destroy_crypto_key_version(
        project_id, location_id, key_ring_id, crypto_key_id, version_id):
    """Schedules a CryptoKeyVersion associated with a given CryptoKey and
    KeyRing for destruction 24 hours in the future."""

    # 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 schedule the CryptoKeyVersion for destruction.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.cryptoKeyVersions().destroy(name=name, body={})
    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}"

# Destroy specific version of the crypto key
kms_client.destroy_crypto_key_version(
  resource,
  Cloudkms::DestroyCryptoKeyVersionRequest.new
)

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

Restore a CryptoKeyVersion

Only a CryptoKeyVersion which is Scheduled for destruction can be Restored. This is done with the method RestoreCryptoKeyVersion.

A CryptoKeyVersion which is Scheduled for destruction can be restored, so that it is not automatically Destroyed. This moves the CryptoKeyVersion from Scheduled for destruction to Disabled.

Command-line

Restore version "42" of CryptoKey "answer" in KeyRing "answers"

gcloud kms keys versions restore 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 RestoreCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for restoring the crypto key Version.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}/cryptoKeyVersions/{versionId}";
          RestoreCryptoKeyVersionRequest restoreRequest = new RestoreCryptoKeyVersionRequest();
          // Restore crypto key version.
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .CryptoKeyVersionsResource.RestoreRequest(cloudKms, restoreRequest, parent);
          var result = request.Execute();
          Console.Write($"Restored Crypto Key Version: {result.Name}");
          return 0;
      }

Go

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

func restoreCryptoKeyVersion(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.Restore(
		parent, &cloudkms.RestoreCryptoKeyVersionRequest{}).Do()
	if err != nil {
		return err
	}
	log.Print("Restored 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;
  }

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

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

    console.log(`Crypto key version ${cryptoKeyVersion.name} restored.`);
  });
});

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.

/**
 * Restore a CryptoKey version.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $version
 * @param string $locationId [optional]
 * @return Google_Service_CloudKMS_CryptoKeyVersion
 */
function restore_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 CryptoKey version.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId,
        $version
    );

    // Restore the CryptoKey version.
    $request = new Google_Service_CloudKMS_RestoreCryptoKeyVersionRequest();
    $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions->restore(
        $parent,
        $request
    );

    printf('Restored 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}"

# Restore specific version of the crypto key
kms_client.restore_crypto_key_version(
  resource,
  Cloudkms::RestoreCryptoKeyVersionRequest.new
)

puts "Restored 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