啟用及停用金鑰版本

在 Cloud KMS 中,用於加密、解密、簽署及驗證資料的加密編譯金鑰內容會儲存在金鑰版本中。金鑰有零個或多個金鑰版本。輪替金鑰時,您會建立新的金鑰版本。

本文將說明如何停用金鑰版本。在金鑰停用期間,您將無法存取以該金鑰加密的資料。如要存取資料,您可以重新啟用金鑰版本。

除非在 Service Health 資訊主頁中另有說明,否則在 1 分鐘內停用金鑰版本通常是一致的。啟用金鑰版本幾乎是即時作業。您也可以使用 Identity and Access Management (IAM) 管理金鑰版本的存取權。IAM 作業在幾秒內保持一致。詳情請參閱「使用身分與存取權管理」。

您也可以永久刪除金鑰版本。視貴機構的政策而定,您可能需要先停用金鑰版本,才能刪除該版本。詳情請參閱「控制金鑰版本銷毀」一文。

停用金鑰版本

您可以在已啟用的狀態下停用金鑰版本。停用金鑰版本前,建議您先確認金鑰是否仍在使用中。您可以查看金鑰使用情形追蹤詳細資料,瞭解金鑰是否用於保護 CMEK 資源。如果任何資源都受到您要停用的金鑰版本保護,請先使用其他金鑰版本重新加密這些資源,再停用金鑰。

控制台

  1. 前往 Google Cloud 控制台的「Key Management」頁面。

    前往「Key Management」(金鑰管理) 頁面

  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 金鑰或金鑰版本。建議您停用所有金鑰版本。停用金鑰的效果會在三小時內生效。

停用金鑰時,您也應撤銷金鑰存取權。身分與存取權管理作業在幾秒內就會一致。您也可以考慮在外部金鑰管理合作夥伴系統中,撤銷 Google Cloud 服務帳戶的存取權。

如要永久移除 Cloud EKM 金鑰與外部金鑰之間的關聯,您可以安排刪除 Cloud EKM 金鑰版本。在排定的銷毀期限過後,系統就會銷毀金鑰。而且這項操作無法復原。金鑰版本遭到刪除後,您就無法再加密資料,也無法解密以 Cloud EKM 金鑰版本加密的資料。即使您使用相同的外部金鑰 URI 或金鑰路徑,也無法重新建立已銷毀的 Cloud EKM 金鑰版本。刪除外部金鑰內容時,建議您先在 Google Cloud 中刪除金鑰或金鑰版本,然後再刪除外部金鑰管理工具中的金鑰內容。

在 Cloud KMS 中停用金鑰或金鑰版本,並不會修改外部金鑰管理合作夥伴系統中的金鑰。

在 Cloud KMS 中刪除手動管理的金鑰版本,不會修改外部金鑰管理合作夥伴系統中的金鑰。在 Cloud KMS 中刪除協調外部金鑰版本,會刪除內部金鑰內容,並向外部金鑰管理合作夥伴系統傳送要求,以便刪除外部金鑰內容。

啟用金鑰版本

您可以在已停用的狀態下啟用金鑰版本。

控制台

  1. 前往 Google Cloud 控制台的「Key Management」頁面。

    前往「Key Management」(金鑰管理) 頁面

  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 管理員角色 (roles/cloudkms.admin)。