启用和停用密钥版本

密钥版本具有状态,用来确定该版本是否可以用于加密和解密。

要启用或停用密钥版本,用户需要相应的 Cloud Identity and Access Management 角色或权限。

  • 预定义的角色 roles/cloudkms.adminroles/ownerroles/editor 可以启用或停用密钥版本。

  • 包含 cloudkms.cryptoKeyVersions.update 权限的自定义角色可以启用或停用密钥版本。

停用已启用的密钥版本

只能停用已启用的密钥版本。可通过使用 state 字段的 UpdateCryptoKeyVersion 方法、映射到 UpdateCryptoKeyVersion 的客户端库方法、gcloud kms keys versions disable 或 Google Cloud Platform Console 来完成停用操作。

Console

  1. 转到 GCP Console 中的加密密钥页面。
    转到“加密密钥”页面

  2. 点击您将停用其密钥版本的密钥所在密钥环的名称。

  3. 点击您要停用其密钥版本的密钥。

  4. 点击您要停用的密钥版本。

  5. 点击停用

  6. 在系统提示您确认停用密钥版本时,请点击停用

命令行

要在 global 位置停用密钥环 answers 中密钥 answer 的版本 42,请运行以下命令:

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

启用已停用的密钥版本

只能启用已停用的密钥版本。可通过使用 state 字段的 UpdateCryptoKeyVersion 方法、映射到 UpdateCryptoKeyVersion 的客户端库方法、gcloud kms keys versions enable 或 Google Cloud Platform Console 来完成启用操作。

启用密钥后,它可即时用于加密和解密数据。

Console

  1. 转到 GCP Console 中的加密密钥页面。
    转到“加密密钥”页面

  2. 点击您将启用其密钥版本的密钥所在密钥环的名称。

  3. 点击您要启用其密钥版本的密钥。

  4. 点击您要启用的密钥版本。

  5. 点击启用

  6. 在系统提示您确认启用密钥版本时,请点击启用

命令行

要在 global 位置启用密钥环 answers 中密钥 answer 的版本 42,请运行以下命令:

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

启用和停用密钥版本时的一致性

启用密钥版本是一种具有高度一致性的操作。启用的密钥版本可立即用于加密和解密数据。停用密钥版本是一种具有最终一致性的操作。密钥版本在停用后的一段时间(平均约 40 分钟,最长 3 小时)内,仍可用于加密和解密数据。如需详细了解密钥版本的一致性,请参阅 Cloud KMS 资源一致性

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud KMS