启用和停用密钥版本

在 Cloud KMS 中,用于加密、解密、签署和验证数据的加密密钥材料存储在密钥版本中。一个密钥具有零个或多个密钥版本。当您轮替密钥时,会创建新的密钥版本。

本主题介绍如何停用密钥版本。在密钥停用期间,无法访问使用该密钥加密的数据。要访问数据,您可以重新启用密钥版本。

停用密钥版本会在几秒钟到三小时内达成一致。启用密钥版本几乎是即时的。您还可以使用 Identity and Access Management (IAM) 管理对密钥版本的访问权限。IAM 操作会在数秒内达成一致。如需了解详情,请参阅使用 IAM

您还可以永久销毁密钥版本。您可能需要先停用某个密钥版本,然后才能将其销毁,具体取决于您的组织政策。如需了解详情,请参阅控制密钥版本销毁

停用密钥版本

您可以停用处于启用state的密钥版本。在停用某个密钥版本之前,我们建议您检查该密钥是否仍在使用中。您可以查看密钥的密钥使用情况跟踪详细信息,了解它是否在保护 CMEK 资源。如果任何资源受您要停用的密钥版本的保护,请在停用该密钥之前,使用其他密钥版本重新加密这些资源。

控制台

  1. 转到 Google Cloud 控制台中的密钥管理页面。

    前往“密钥管理”页面

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

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

  4. 选中要停用的密钥版本旁边的复选框。

  5. 点击标头中的停用

  6. 在确认提示中,点击停用

gcloud

如需在命令行上使用 Cloud KMS,请先安装或升级到最新版本的 Google Cloud CLI

gcloud kms keys versions disable key-version \
    --key key \
    --keyring key-ring \
    --location location

key-version 替换为要停用的密钥的版本。将 key 替换为密钥的名称。将 key-ring 替换为密钥所在的密钥环的名称。将 location 替换为密钥环的 Cloud KMS 位置。

如需了解所有标志和可能值,请使用 --help 标志运行命令。

C#

要运行此代码,请先设置 C# 开发环境安装 Cloud KMS C# SDK


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class DisableKeyVersionSample
{
    public CryptoKeyVersion DisableKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion
        {
            CryptoKeyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId),
            State = CryptoKeyVersion.Types.CryptoKeyVersionState.Disabled,
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "state" },
        };

        // Call the API.
        CryptoKeyVersion result = client.UpdateCryptoKeyVersion(keyVersion, fieldMask);

        // Return the result.
        return result;
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Cloud KMS Go SDK

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	fieldmask "google.golang.org/genproto/protobuf/field_mask"
)

// disableKeyVersion disables the specified key version on Cloud KMS.
func disableKeyVersion(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.UpdateCryptoKeyVersionRequest{
		CryptoKeyVersion: &kmspb.CryptoKeyVersion{
			Name:  name,
			State: kmspb.CryptoKeyVersion_DISABLED,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"state"},
		},
	}

	// Call the API.
	result, err := client.UpdateCryptoKeyVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key version: %w", err)
	}
	fmt.Fprintf(w, "Disabled key version: %s\n", result)
	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Cloud KMS Java SDK

import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState;
import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class DisableKeyVersion {

  public void disableKeyVersion() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String keyVersionId = "123";
    disableKeyVersion(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Disable a key version from use.
  public void disableKeyVersion(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Build the updated key version, setting it to disbaled.
      CryptoKeyVersion keyVersion =
          CryptoKeyVersion.newBuilder()
              .setName(keyVersionName.toString())
              .setState(CryptoKeyVersionState.DISABLED)
              .build();

      // Create a field mask of updated values.
      FieldMask fieldMask = FieldMaskUtil.fromString("state");

      // Disable the key version.
      CryptoKeyVersion response = client.updateCryptoKeyVersion(keyVersion, fieldMask);
      System.out.printf("Disabled key version: %s%n", response.getName());
    }
  }
}

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Cloud KMS Node.js SDK

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const versionId = '123';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function disableKeyVersion() {
  const [version] = await client.updateCryptoKeyVersion({
    cryptoKeyVersion: {
      name: versionName,
      state: 'DISABLED',
    },
    updateMask: {
      paths: ['state'],
    },
  });

  console.log(`Disabled key version: ${version.name}`);
  return version;
}

return disableKeyVersion();

PHP

要运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Cloud KMS PHP SDK

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKeyVersion;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionState;
use Google\Cloud\Kms\V1\UpdateCryptoKeyVersionRequest;
use Google\Protobuf\FieldMask;

function disable_key_version(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key',
    string $versionId = '123'
): CryptoKeyVersion {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key version name.
    $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Create the updated version.
    $keyVersion = (new CryptoKeyVersion())
        ->setName($keyVersionName)
        ->setState(CryptoKeyVersionState::DISABLED);

    // Create the field mask.
    $updateMask = (new FieldMask())
        ->setPaths(['state']);

    // Call the API.
    $updateCryptoKeyVersionRequest = (new UpdateCryptoKeyVersionRequest())
        ->setCryptoKeyVersion($keyVersion)
        ->setUpdateMask($updateMask);
    $disabledVersion = $client->updateCryptoKeyVersion($updateCryptoKeyVersionRequest);
    printf('Disabled key version: %s' . PHP_EOL, $disabledVersion->getName());

    return $disabledVersion;
}

Python

要运行此代码,请先设置 Python 开发环境安装 Cloud KMS Python SDK

from google.cloud import kms

def disable_key_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.CryptoKeyVersion:
    """
    Disable a key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        version_id (string): ID of the key version to disable (e.g. '1').

    Returns:
        CryptoKeyVersion: The version.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    key_version = {
        "name": key_version_name,
        "state": kms.CryptoKeyVersion.CryptoKeyVersionState.DISABLED,
    }

    # Build the update mask.
    update_mask = {"paths": ["state"]}

    # Call the API.
    disabled_version = client.update_crypto_key_version(
        request={"crypto_key_version": key_version, "update_mask": update_mask}
    )
    print(f"Disabled key version: {disabled_version.name}")
    return disabled_version

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Cloud KMS Ruby SDK

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"
# version_id  = "123"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the key version name.
key_version_name = client.crypto_key_version_path project:            project_id,
                                                  location:           location_id,
                                                  key_ring:           key_ring_id,
                                                  crypto_key:         key_id,
                                                  crypto_key_version: version_id

# Create the updated version.
version = {
  name:  key_version_name,
  state: :DISABLED
}

# Create the field mask.
update_mask = { paths: ["state"] }

# Call the API.
disabled_version = client.update_crypto_key_version crypto_key_version: version, update_mask: update_mask
puts "Disabled key version: #{disabled_version.name}"

在您提交请求后,密钥版本的状态会更改为“已停用”。

已停用的密钥版本是计费资源。

停用或销毁外部密钥

要暂时停用 Cloud EKM 密钥与外部密钥之间的关联,您可以停用 Cloud EKM 密钥或密钥版本。建议停用所有密钥版本。停用密钥会在三小时内生效。

停用密钥后,您还应该撤消对该密钥的访问权限。IAM 操作会在数秒内达成一致。此外,请考虑撤消 Google Cloud 服务账号在外部密钥管理合作伙伴系统中的访问权限。

永久移除 Cloud EKM 密钥与外部密钥之间的关联,您可以安排销毁 Cloud EKM 密钥版本。在安排的销毁期过后,密钥将被销毁。销毁密钥版本是永久性操作。密钥版本销毁后,您无法再加密数据或解密使用 Cloud EKM 密钥版本加密的数据。即使您使用相同的外部密钥 URI 或密钥路径,也无法重新创建已销毁的 Cloud EKM 密钥版本。销毁外部密钥材料时,我们建议先销毁 Google Cloud 中的密钥或密钥版本,然后仅在 Cloud EKM 密钥销毁后销毁外部密钥管理器中的密钥材料。

在 Cloud KMS 中停用密钥或密钥版本并不会修改外部密钥管理合作伙伴系统中的密钥。

销毁 Cloud KMS 中手动管理的密钥版本不会修改外部密钥管理合作伙伴系统中的密钥。销毁 Cloud KMS 中的协调外部密钥版本会销毁内部密钥材料,并向外部密钥管理合作伙伴系统发送请求以销毁外部密钥材料。

启用密钥版本

您可以在state中启用密钥版本。

控制台

  1. 转到 Google Cloud 控制台中的密钥管理页面。

    前往“密钥管理”页面

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

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

  4. 选中要启用的密钥版本旁边的复选框。

  5. 点击标头中的启用

  6. 在确认提示中,点击启用

gcloud

如需在命令行上使用 Cloud KMS,请先安装或升级到最新版本的 Google Cloud CLI

gcloud kms keys versions enable key-version \
    --key key \
    --keyring key-ring \
    --location location

key-version 替换为要启用的密钥的版本。将 key 替换为密钥名称。将 key-ring 替换为密钥所在的密钥环的名称。将 location 替换为密钥环的 Cloud KMS 位置。

如需了解所有标志和可能值,请使用 --help 标志运行命令。

C#

要运行此代码,请先设置 C# 开发环境安装 Cloud KMS C# SDK


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class EnableKeyVersionSample
{
    public CryptoKeyVersion EnableKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion
        {
            CryptoKeyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId),
            State = CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled,
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "state" },
        };

        // Call the API.
        CryptoKeyVersion result = client.UpdateCryptoKeyVersion(keyVersion, fieldMask);

        // Return the result.
        return result;
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Cloud KMS Go SDK

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	fieldmask "google.golang.org/genproto/protobuf/field_mask"
)

// enableKeyVersion disables the specified key version on Cloud KMS.
func enableKeyVersion(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.UpdateCryptoKeyVersionRequest{
		CryptoKeyVersion: &kmspb.CryptoKeyVersion{
			Name:  name,
			State: kmspb.CryptoKeyVersion_ENABLED,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"state"},
		},
	}

	// Call the API.
	result, err := client.UpdateCryptoKeyVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key version: %w", err)
	}
	fmt.Fprintf(w, "Enabled key version: %s\n", result)
	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Cloud KMS Java SDK

import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState;
import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class EnableKeyVersion {

  public void enableKeyVersion() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String keyVersionId = "123";
    enableKeyVersion(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Enable a disabled key version to be used again.
  public void enableKeyVersion(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Build the updated key version, setting it to enabled.
      CryptoKeyVersion keyVersion =
          CryptoKeyVersion.newBuilder()
              .setName(keyVersionName.toString())
              .setState(CryptoKeyVersionState.ENABLED)
              .build();

      // Create a field mask of updated values.
      FieldMask fieldMask = FieldMaskUtil.fromString("state");

      // Enable the key version.
      CryptoKeyVersion response = client.updateCryptoKeyVersion(keyVersion, fieldMask);
      System.out.printf("Enabled key version: %s%n", response.getName());
    }
  }
}

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Cloud KMS Node.js SDK

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const versionId = '123';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function enableKeyVersion() {
  const [version] = await client.updateCryptoKeyVersion({
    cryptoKeyVersion: {
      name: versionName,
      state: 'ENABLED',
    },
    updateMask: {
      paths: ['state'],
    },
  });

  console.log(`Enabled key version: ${version.name}`);
  return version;
}

return enableKeyVersion();

PHP

要运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Cloud KMS PHP SDK

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKeyVersion;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionState;
use Google\Cloud\Kms\V1\UpdateCryptoKeyVersionRequest;
use Google\Protobuf\FieldMask;

function enable_key_version(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key',
    string $versionId = '123'
): CryptoKeyVersion {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key version name.
    $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Create the updated version.
    $keyVersion = (new CryptoKeyVersion())
        ->setName($keyVersionName)
        ->setState(CryptoKeyVersionState::ENABLED);

    // Create the field mask.
    $updateMask = (new FieldMask())
        ->setPaths(['state']);

    // Call the API.
    $updateCryptoKeyVersionRequest = (new UpdateCryptoKeyVersionRequest())
        ->setCryptoKeyVersion($keyVersion)
        ->setUpdateMask($updateMask);
    $enabledVersion = $client->updateCryptoKeyVersion($updateCryptoKeyVersionRequest);
    printf('Enabled key version: %s' . PHP_EOL, $enabledVersion->getName());

    return $enabledVersion;
}

Python

要运行此代码,请先设置 Python 开发环境安装 Cloud KMS Python SDK

from google.cloud import kms

def enable_key_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.CryptoKeyVersion:
    """
    Enable a key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        version_id (string): ID of the key version to enable (e.g. '1').

    Returns:
        CryptoKeyVersion: The version.

    """
    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    key_version = {
        "name": key_version_name,
        "state": kms.CryptoKeyVersion.CryptoKeyVersionState.ENABLED,
    }

    # Build the update mask.
    update_mask = {"paths": ["state"]}

    # Call the API.
    enabled_version = client.update_crypto_key_version(
        request={"crypto_key_version": key_version, "update_mask": update_mask}
    )
    print(f"Enabled key version: {enabled_version.name}")
    return enabled_version

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Cloud KMS Ruby SDK

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"
# version_id  = "123"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the key version name.
key_version_name = client.crypto_key_version_path project:            project_id,
                                                  location:           location_id,
                                                  key_ring:           key_ring_id,
                                                  crypto_key:         key_id,
                                                  crypto_key_version: version_id

# Create the updated version.
version = {
  name:  key_version_name,
  state: :ENABLED
}

# Create the field mask.
update_mask = { paths: ["state"] }

# Call the API.
enabled_version = client.update_crypto_key_version crypto_key_version: version, update_mask: update_mask
puts "Enabled key version: #{enabled_version.name}"

在您提交请求后,密钥版本的状态会更改为“已启用”。

必需的 IAM 权限

要启用或停用密钥版本,调用者需要拥有密钥、密钥环或项目、文件夹或组织的 cloudkms.cryptoKeyVersions.update IAM 权限。

此权限授予了 Cloud KMS Admin 角色 (roles/cloudkms.admin)。