重新加密数据

本主题介绍了如何重新加密数据。如果您怀疑存在未经授权使用密钥的情况,则应当重新加密受该密钥保护的数据,然后停用或安排销毁先前的密钥版本。

准备工作

此场景需要以下条件。

  • 您已使用 Cloud KMS 加密了数据

  • 用于加密的密钥版本并非处于已停用、计划销毁或已销毁状态。您使用此密钥版本对已加密的数据进行解密。

  • 你已经对密钥进行了轮替密钥轮替会创建新的主密钥版本。您使用新的主密钥版本重新加密数据。

重新加密数据工作流程

使用以下步骤,重新加密数据并停用或安排销毁最初用于加密的密钥版本。

  1. 使用先前的密钥版本解密数据

  2. 使用新的主密钥版本重新加密数据

  3. 停用或计划销毁先前的密钥版本

使用先前的密钥版本解密数据

Cloud KMS 会自动使用正确的密钥版本对数据进行解密,前提是该密钥版本并非处于已停用、计划销毁或已销毁状态。以下示例显示了如何解密数据。示例与加密和解密使用的解密代码相同。

命令行

要解密数据,请提供相应的密钥信息,指定要解密的加密文件(密文文件)的名称,然后指定将包含解密后内容的文件的名称。

gcloud kms decrypt \
  --location=global \
  --keyring=my-key-ring \
  --key=my-key \
  --ciphertext-file=FILEPATH_AND_FILENAME_TO_DECRYPT \
  --plaintext-file=FILEPATH_AND_FILENAME_TO_DECRYPT.dec

decrypt 命令支持可选 --additional-authenticated-data- file 标志,以指定包含经过身份验证的额外数据的文件。包含经过身份验证的额外数据的文件不得大于 64 KiB。

如果 --ciphertext-file--additional-authenticated-data-file 设置为 -,则将从 stdin 读取该文件。同样,如果 --plaintext-file 设置为 -,则解密后的明文将写入 stdout

以下 decrypt 示例显示了如何指定经过身份验证的额外数据。

gcloud kms decrypt \
  --location=global \
  --keyring=my-key-ring \
  --key=my-key \
  --additional-authenticated-data-file=ADDITIONAL_AUTHENTICATED_DATA_FILEPATH_AND_FILENAME \
  --ciphertext-file=FILEPATH_AND_FILENAME_TO_DECRYPT \
  --plaintext-file=FILEPATH_AND_FILENAME_TO_DECRYPT.dec

协议

从 Cloud KMS 中以 JSON 格式返回的解密后文本使用 base64 进行编码。如需了解如何使用 base64 进行编码和解码,请参阅 Base64 编码

要对加密后的数据进行解密,请发出 POST 请求并提供相应的项目和密钥信息,并在请求正文的 ciphertext 字段中指定要解密的加密后的文本(密文)。将 API_KEY 替换为有效的 API 密钥。如需了解如何生成 API 密钥,请参阅访问 API

POST https://cloudkms.googleapis.com/v1/projects/project_id/locations/global/keyRings/keyring_name/cryptoKeys/cryptoKey_name:decrypt&key=API_KEY
{
  "ciphertext": "CiQAhMwwBo61cHas7dDgifrUFs5zNzBJ2uZtVFq4ZPEl6fUVT4kSmQ...",
}

以下是使用 curl 的示例:

curl -s -X POST "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/global/keyRings/KEYRING_NAME/cryptoKeys/CRYPTOKEY_NAME:decrypt" \
  -d "{\"ciphertext\":\"ENCRYPTED_CONTENT\"}" \
  -H "Authorization:Bearer API_KEY"\
  -H "Content-Type:application/json"

C#

        public static void Decrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId,
    string ciphertextFile, string plaintextFile)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            byte[] ciphertext = File.ReadAllBytes(ciphertextFile);
            DecryptResponse result = client.Decrypt(cryptoKeyName, ByteString.CopyFrom(ciphertext));

            // Output decrypted data to a file.
            File.WriteAllBytes(plaintextFile, result.Plaintext.ToByteArray());
            Console.Write($"Decrypted file created: {plaintextFile}");
        }

Go

// decrypt will decrypt the input ciphertext bytes using the specified symmetric key
// example keyName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID"
func decryptSymmetric(keyName string, ciphertext []byte) ([]byte, error) {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return nil, err
	}

	// Build the request.
	req := &kmspb.DecryptRequest{
		Name:       keyName,
		Ciphertext: ciphertext,
	}
	// Call the API.
	resp, err := client.Decrypt(ctx, req)
	if err != nil {
		return nil, err
	}
	return resp.Plaintext, nil
}

Java

/**
 * Decrypts the provided ciphertext with the specified crypto key.
 */
public static byte[] decrypt(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] ciphertext)
    throws IOException {

  // Create the KeyManagementServiceClient using try-with-resources to manage client cleanup.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey
    String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);

    // Decrypt the ciphertext with Cloud KMS.
    DecryptResponse response = client.decrypt(resourceName, ByteString.copyFrom(ciphertext));

    // Extract the plaintext from the response.
    return response.getPlaintext().toByteArray();
  }
}

Node.js

async function decrypt(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
  ciphertextFileName = './path/to/plaintext.txt.encrypted',
  plaintextFileName = './path/to/plaintext.txt.decrypted'
) {
  const fs = require('fs');
  const {promisify} = require('util');

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring, e.g. "global"
  const locationId = 'global';

  // Reads the file to be decrypted
  const readFile = promisify(fs.readFile);
  const contentsBuffer = await readFile(ciphertextFileName);
  const name = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );
  const ciphertext = contentsBuffer.toString('base64');

  // Decrypts the file using the specified crypto key
  const [result] = await client.decrypt({name, ciphertext});

  // Writes the decrypted file to disk
  const writeFile = promisify(fs.writeFile);
  await writeFile(plaintextFileName, Buffer.from(result.plaintext, 'base64'));
  console.log(
    `Decrypted ${ciphertextFileName}, result saved to ${plaintextFileName}.`
  );
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKey;

/** 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';
// $ciphertextFileName = 'The path to the file containing ciphertext to decrypt';
// $plaintextFileName = 'The path to write the plaintext';

$kms = new KeyManagementServiceClient();

// The resource name of the CryptoKey.
$cryptoKey = new CryptoKey();
$cryptoKeyName = $kms->cryptoKeyName($projectId, $locationId, $keyRingId, $cryptoKeyId);

$ciphertext = file_get_contents($ciphertextFileName);
$response = $kms->decrypt($cryptoKeyName, $ciphertext);

// Write the encrypted text to a file.
file_put_contents($plaintextFileName, $response->getPlaintext());
printf('Saved decrypted text to %s' . PHP_EOL, $plaintextFileName);

Python

def decrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id,
                      ciphertext):
    """Decrypts input ciphertext using the provided symmetric CryptoKey."""

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the CryptoKey.
    name = client.crypto_key_path_path(project_id, location_id, key_ring_id,
                                       crypto_key_id)
    # Use the KMS API to decrypt the data.
    response = client.decrypt(name, ciphertext)
    return response.plaintext

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"
# ciphertext_file = "File to decrypt"
# plaintext_file  = "File to store decrypted data"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The crypto key to use
crypto_key = CloudKMS::KeyManagementServiceClient.crypto_key_path(
  project_id, location_id, key_ring_id, crypto_key_id
)

# Read the encrypted data from the file
ciphertext = File.open(ciphertext_file, "rb", &:read)

# Use the KMS API to decrypt the data
response = client.decrypt crypto_key, ciphertext

# Write the decrypted text to the output file
File.open(plaintext_file, "wb") { |f| f.write response.plaintext }

puts "Saved decrypted #{ciphertext_file} as #{plaintext_file}"

使用新的主密钥版本重新加密数据

Cloud KMS 自动使用新的主密钥版本来加密数据。以下示例显示了如何加密数据。示例与加密和解密中使用的加密代码相同。

命令行

要加密数据,请提供相应的密钥信息,指定要加密的明文文件的名称,然后指定包含加密后内容的文件的名称。

gcloud kms encrypt \
  --location=global  \
  --keyring=my-key-ring \
  --key=my-key \
  --plaintext-file=FILEPATH_AND_FILENAME_TO_ENCRYPT.dec \
  --ciphertext-file=FILEPATH_AND_FILENAME.enc

明文文件不得大于 64 KiB。

encrypt 命令支持可选 --additional-authenticated-data-file 标志,以指定包含经过身份验证的额外数据的文件。包含经过身份验证的额外数据的文件不得大于 64 KiB。

如果 --plaintext-file--additional-authenticated-data-file 设置为 -,则将从 stdin 读取该文件。同样,如果 --ciphertext-file 设置为 -,则密文将写入 stdout

encrypt 命令支持可选 --version 标志,以指示要用于加密的密钥的版本。默认情况下,使用主版本。

以下 encrypt 示例显示了如何指定版本密钥和经过身份验证的额外数据。

gcloud kms encrypt \
  --location=global  \
  --keyring=my-key-ring \
  --key=my-key \
  --version=my-key-version \
  --additional-authenticated-data-file=ADDITIONAL_AUTHENTICATED_DATA_FILEPATH_AND_FILENAME \
  --plaintext-file=FILEPATH_AND_FILENAME_TO_ENCRYPT.dec \
  --ciphertext-file=FILEPATH_AND_FILENAME.enc

协议

以 JSON 格式发送到 Cloud KMS 的要加密的内容必须使用 base64 编码。如需了解如何使用 base64 进行编码和解码,请参阅 Base64 编码

要加密数据,请发出 POST 请求并提供相应的项目和密钥信息,并在请求正文的 plaintext 字段中指定要加密的 base64 编码文本。将 API_KEY 替换为有效的 API 密钥。如需了解如何生成 API 密钥,请参阅访问 API

POST https://cloudkms.googleapis.com/v1/projects/project_id/locations/global/keyRings/keyring_name/cryptoKeys/cryptoKey_name:encrypt&key=API_KEY
{
  "plaintext": "BASE64_ENCODED_INPUT",
}

以下是使用 curl 的示例:

curl -s -X POST "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/global/keyRings/KEYRING_NAME/cryptoKeys/CRYPTOKEY_NAME:encrypt" \
  -d "{\"plaintext\":\"BASE64_ENCODED_INPUT\"}" \
  -H "Authorization:Bearer API_KEY"\
  -H "Content-Type:application/json"

C#

        public static void Encrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId,
string plaintextFile, string ciphertextFile)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            byte[] plaintext = File.ReadAllBytes(plaintextFile);
            CryptoKeyPathName pathName = CryptoKeyPathName.Parse(cryptoKeyName.ToString());
            EncryptResponse result = client.Encrypt(pathName, ByteString.CopyFrom(plaintext));

            // Output encrypted data to a file.
            File.WriteAllBytes(ciphertextFile, result.Ciphertext.ToByteArray());
            Console.Write($"Encrypted file created: {ciphertextFile}");
        }

Go

// encrypt will encrypt the input plaintext with the specified symmetric key
// example keyName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID"
func encryptSymmetric(keyName string, plaintext []byte) ([]byte, error) {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return nil, err
	}

	// Build the request.
	req := &kmspb.EncryptRequest{
		Name:      keyName,
		Plaintext: plaintext,
	}
	// Call the API.
	resp, err := client.Encrypt(ctx, req)
	if err != nil {
		return nil, err
	}
	return resp.Ciphertext, nil
}

Java

/**
 * Encrypts the given plaintext using the specified crypto key.
 */
public static byte[] encrypt(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] plaintext)
    throws IOException {

  // Create the KeyManagementServiceClient using try-with-resources to manage client cleanup.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey
    String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);

    // Encrypt the plaintext with Cloud KMS.
    EncryptResponse response = client.encrypt(resourceName, ByteString.copyFrom(plaintext));

    // Extract the ciphertext from the response.
    return response.getCiphertext().toByteArray();
  }
}

Node.js

async function encrypt(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
  plaintextFileName = './path/to/plaintext.txt',
  ciphertextFileName = './path/to/plaintext.txt.encrypted'
) {
  const fs = require('fs');
  const {promisify} = require('util');

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring, e.g. "global"
  const locationId = 'global';

  // Reads the file to be encrypted
  const readFile = promisify(fs.readFile);
  const contentsBuffer = await readFile(plaintextFileName);
  const plaintext = contentsBuffer.toString('base64');
  const name = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );

  // Encrypts the file using the specified crypto key
  const [result] = await client.encrypt({name, plaintext});
  const writeFile = promisify(fs.writeFile);
  await writeFile(ciphertextFileName, Buffer.from(result.ciphertext, 'base64'));
  console.log(`Encrypted ${plaintextFileName} using ${result.name}.`);
  console.log(`Result saved to ${ciphertextFileName}.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

/** 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';
// $plaintextFileName = 'The path to the file containing plaintext to encrypt';
// $ciphertextFileName = 'The path to write the ciphertext';

$kms = new KeyManagementServiceClient();

// The resource name of the CryptoKey.
$cryptoKeyName = $kms->cryptoKeyName($projectId, $locationId, $keyRingId, $cryptoKeyId);

$plaintext = file_get_contents($plaintextFileName);
$response = $kms->encrypt($cryptoKeyName, $plaintext);

// Write the encrypted text to a file.
file_put_contents($ciphertextFileName, $response->getCiphertext());
printf('Saved encrypted text to %s' . PHP_EOL, $ciphertextFileName);

Python

def encrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id,
                      plaintext):
    """Encrypts input plaintext data using the provided symmetric CryptoKey."""

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the CryptoKey.
    name = client.crypto_key_path_path(project_id, location_id, key_ring_id,
                                       crypto_key_id)

    # Use the KMS API to encrypt the data.
    response = client.encrypt(name, plaintext)
    return response.ciphertext

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"
# plaintext_file  = "File to encrypt"
# ciphertext_file = "File to store encrypted input data"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The crypto key to use
crypto_key = CloudKMS::KeyManagementServiceClient.crypto_key_path(
  project_id, location_id, key_ring_id, crypto_key_id
)

# Read the secret data from the file
plaintext = File.open(plaintext_file, "rb", &:read)

# Use the KMS API to encrypt the data
response = client.encrypt crypto_key, plaintext

# Write the encrypted binary data to the output file
File.open(ciphertext_file, "wb") { |f| f.write response.ciphertext }

puts "Saved encrypted #{plaintext_file} as #{ciphertext_file}"

停用或计划销毁先前的密钥版本

如果您为了响应可疑突发事件而轮替密钥,重新加密数据后,请停用安排销毁先前的密钥版本。

停用已启用的密钥版本

只有已启用的密钥版本才能被停用。您可以通过 UpdateCryptoKeyVersion 方法实现这一目的。

命令行

要在 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(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
	}
	log.Printf("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});
  cryptoKeyVersion.state = 'DISABLED';

  // Disables a crypto key version
  const [result] = await client.updateCryptoKeyVersion({
    cryptoKeyVersion,
    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."""

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

安排销毁密钥版本

只有处于已启用或已停用状态的密钥版本可以安排进行销毁。您可以通过 DestroyCryptoKeyVersion 方法实现这一目的。

为了防止发生意外和来自恶意个人的损害,使用 DestroyCryptoKeyVersion 时,密钥材料不会立即被销毁。相反,密钥版本的状态将更改为计划销毁,此过程持续 24 小时,之后它会自动被销毁。这一安全备用方案不可被覆盖。如果您在安排销毁后 24 小时内决定不销毁密钥版本,则可以恢复密钥版本

销毁是指密钥材料的删除,但版本的记录仍然存在(例如,版本号无法重复使用)。这一过程不可逆:使用此版本加密的任何数据都不可恢复。

命令行

global 位置销毁密钥环 answers 中密钥 answer 的版本 42

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

C#

      public static void DestroyCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
      {
          KeyManagementServiceClient client = KeyManagementServiceClient.Create();

          // The CryptoKeyVersion to destroy.
          CryptoKeyVersionName versionName =
              new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId);

          CryptoKeyVersion result = client.DestroyCryptoKeyVersion(versionName);

          Console.Write($"Destroyed Crypto Key Version: {result.Name}");
      }

Go

// destroyCryptoKeyVersion marks a specified key version for deletion. The key can be restored if requested within 24 hours.
// example keyVersionName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
func destroyCryptoKeyVersion(keyVersionName string) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return err
	}
	// Build the request.
	req := &kmspb.DestroyCryptoKeyVersionRequest{
		Name: keyVersionName,
	}
	// Call the API.
	result, err := client.DestroyCryptoKeyVersion(ctx, req)
	if err != nil {
		return err
	}
	log.Printf("Destroyed crypto key version: %s", result)
	return nil
}

Java

/**
 * 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.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey version
    String versionName = CryptoKeyVersionName.format(
        projectId, locationId, keyRingId, cryptoKeyId, version);

    // Destroy the cryptoKey version
    CryptoKeyVersion destroyed = client.destroyCryptoKeyVersion(versionName);

    return destroyed;
  }
}

Node.js

async function destroyCryptoKeyVersion(
  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 version
  const name = client.cryptoKeyVersionPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId,
    version
  );

  // destroys a crypto key version
  const [result] = await client.destroyCryptoKeyVersion({name});
  console.log(`Crypto key version ${result.name} destroyed.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

/** 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->destroyCryptoKeyVersion($cryptoKeyVersionName);

printf('Destroyed version %s for cryptoKey %s in keyRing %s' . PHP_EOL, $version, $cryptoKeyId, $keyRingId);

Python

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.
    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 mark the CryptoKeyVersion for destruction.
    response = client.destroy_crypto_key_version(name)

    # Print results
    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

# The crypto key version to destroy
version = CloudKMS::KeyManagementServiceClient.crypto_key_version_path(
  project_id, location_id, key_ring_id, crypto_key_id, version_id
)

# Destroy the crypto key version
destroyed = client.destroy_crypto_key_version version

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

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

发送以下问题的反馈:

此网页
Cloud KMS 文档