Cómo volver a encriptar datos

En este tema, se muestra cómo volver a encriptar los datos. Si sospechas que una clave se usa sin autorización, debes volver a encriptar los datos que esta protege y, luego, inhabilitar o programar la destrucción de la versión de clave anterior.

Antes de comenzar

Para esta situación, se requieren estas condiciones:

  • Haber encriptado datos mediante Cloud KMS.

  • La versión de clave que usaste en la encriptación no debe estar inhabilitada, programada para su destrucción ni destruida. Usarás esta versión de clave para desencriptar los datos encriptados.

  • Haber rotado claves. Con la rotación de claves, se crea una versión de clave primaria nueva. Usarás esta versión de clave primaria nueva para volver a encriptar los datos.

Flujo de trabajo para volver a encriptar los datos

Sigue estos pasos para volver a encriptar los datos y también inhabilitar o programar la destrucción de la versión de clave que usaste originalmente.

  1. Desencripta los datos con la versión de clave anterior.

  2. Vuelve a encriptar los datos con la versión de clave primaria nueva.

  3. Inhabilita o programa la destrucción de la versión de clave anterior.

Desencripta los datos con la versión de clave anterior

De manera automática, Cloud KMS usa la versión de clave correcta para desencriptar los datos, siempre y cuando la versión de clave no esté inhabilitada, programada para su destrucción ni destruida. En los siguientes ejemplos, se muestra cómo desencriptar los datos. Este código de desencriptación es el mismo que se usa en Encripta y desencripta.

Línea de comandos

Para desencriptar los datos, proporciona la información de la clave adecuada, especifica el nombre del archivo encriptado (archivo cifrado) que se desencriptará y el nombre del archivo en el que se guardará el contenido desencriptado.

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

El comando decrypt admite la marca opcional --additional-authenticated-data- file que permite especificar un archivo que contenga datos autenticados adicionales. El tamaño del archivo de datos autenticados adicionales no debe superar los 64 KiB.

Si configuras las marcas --ciphertext-file o --additional-authenticated-data-file como -, el archivo se lee desde stdin. De manera similar, si configuras la marca --plaintext-file como -, el texto sin formato desencriptado se escribe en stdout.

En el siguiente ejemplo de decrypt, se muestra cómo especificar los datos autenticados adicionales.

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

Protocolo

El texto desencriptado que se muestra en el archivo JSON de Cloud KMS tiene la codificación Base 64. Para obtener más información sobre la codificación y decodificación con Base 64, consulta Codificación Base 64.

Para desencriptar datos encriptados, haz una solicitud POST y proporciona la información de proyecto y clave que corresponda, y especifica el texto encriptado (cifrado) que se desencriptará en el campo ciphertext del cuerpo de la solicitud. Reemplaza API_KEY por una clave de API válida. Consulta Accede a la API para obtener información sobre cómo generar una clave de API.

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

En este ejemplo, se usa 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 object Decrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId,
string ciphertextFile, string plaintextFile)
    {
        var cloudKms = CreateAuthorizedClient();
        // Generate the full path of the crypto key to use for encryption.
        var cryptoKey = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}";
        DecryptRequest decryptRequest = new DecryptRequest();
        byte[] ciphertext = File.ReadAllBytes(ciphertextFile);
        decryptRequest.Ciphertext = Convert.ToBase64String(ciphertext);
        Console.WriteLine($"dataToDecrypt.Ciphertext: {decryptRequest.Ciphertext}");
        var result = cloudKms.Projects.Locations.KeyRings.CryptoKeys.Decrypt(name: cryptoKey, body: decryptRequest).Execute();
        // Output decrypted data to a file.
        File.WriteAllBytes(plaintextFile, Convert.FromBase64String(result.Plaintext));
        Console.Write($"Decrypted file created: {plaintextFile}");
        return 0;
    }

Go

func decrypt(projectID, locationID, keyRingID, cryptoKeyID string, ciphertext []byte) ([]byte, error) {
	ctx := context.Background()
	client, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return nil, err
	}

	cloudkmsService, err := cloudkms.New(client)
	if err != nil {
		return nil, err
	}

	parentName := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
		projectID, locationID, keyRingID, cryptoKeyID)

	req := &cloudkms.DecryptRequest{
		Ciphertext: base64.StdEncoding.EncodeToString(ciphertext),
	}
	resp, err := cloudkmsService.Projects.Locations.KeyRings.CryptoKeys.Decrypt(parentName, req).Do()
	if err != nil {
		return nil, err
	}
	return base64.StdEncoding.DecodeString(resp.Plaintext)
}

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 Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the cryptoKey
  String cryptoKeyName = String.format(
      "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
      projectId, locationId, keyRingId, cryptoKeyId);

  DecryptRequest request = new DecryptRequest().encodeCiphertext(ciphertext);
  DecryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
      .decrypt(cryptoKeyName, request)
      .execute();

  return response.decodePlaintext();
}

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');

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

  // Writes the dencrypted 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

/**
 * Decrypt a text file.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $ciphertextFileName The path to the ciphertext file to decrypt.
 * @param string $plaintextFileName The path to write the decrypted plaintext file.
 * @param string $locationId [optional]
 * @return null
 */
function decrypt($projectId, $keyRingId, $cryptoKeyId, $ciphertextFileName, $plaintextFileName, $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.
    $name = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId
    );

    // Use the KMS API to decrypt the text.
    $ciphertext = base64_encode(file_get_contents($ciphertextFileName));
    $request = new Google_Service_CloudKMS_DecryptRequest();
    $request->setCiphertext($ciphertext);
    $response = $kms->projects_locations_keyRings_cryptoKeys->decrypt(
        $name,
        $request
    );

    // Write the decrypted text to a file.
    file_put_contents($plaintextFileName, base64_decode($response['plaintext']));
    printf('Saved decrypted text to %s' . PHP_EOL, $plaintextFileName);
}

Python

def decrypt(project_id, location_id, key_ring_id, crypto_key_id,
            ciphertext_file_name, plaintext_file_name):
    """Decrypts data from ciphertext_file_name that was previously encrypted
    using the provided CryptoKey and saves it to plaintext_file_name."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the CryptoKey.
    name = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}'.format(
        project_id, location_id, key_ring_id, crypto_key_id)

    # Read encrypted data from the input file.
    with io.open(ciphertext_file_name, 'rb') as ciphertext_file:
        ciphertext = ciphertext_file.read()

    # Use the KMS API to decrypt the data.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.decrypt(
        name=name,
        body={'ciphertext': base64.b64encode(ciphertext).decode('ascii')})
    response = request.execute()
    plaintext = base64.b64decode(response['plaintext'].encode('ascii'))

    # Write the decrypted data to a file.
    with io.open(plaintext_file_name, 'wb') as plaintext_file:
        plaintext_file.write(plaintext)

    print('Saved plaintext to {}.'.format(plaintext_file_name))

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/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
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}/cryptoKeys/#{crypto_key_id}"

# Read the encrypted data from the file
ciphertext = File.read ciphertext_file

request = Cloudkms::DecryptRequest.new ciphertext: ciphertext

# Use the KMS API to decrypt the data
response = kms_client.decrypt_crypto_key resource, request

# Write the decrypted text to the output file
File.write plaintext_file, response.plaintext

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

Vuelve a encriptar los datos con la versión de clave primaria nueva

Cloud KMS usa la versión de clave primaria nueva de manera automática para encriptar los datos. En los siguientes ejemplos, se muestra cómo hacerlo. Este código de encriptación es el mismo que se usa en Encripta y desencripta.

Línea de comandos

Para encriptar datos, proporciona la información de clave correcta, especifica el nombre del archivo de texto sin formato que encriptarás y también el nombre del archivo que incluirá el contenido encriptado.

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

El tamaño del archivo de texto sin formato no debe superar los 64 KiB.

El comando encrypt admite la marca opcional --additional-authenticated-data-file que permite especificar un archivo que contenga datos autenticados adicionales. El tamaño del archivo de datos autenticados adicionales no debe superar los 64 KiB.

Si configuras las marcas --plaintext-file o --additional-authenticated-data-file como -, el archivo se lee desde stdin. De manera similar, si configuras la marca --ciphertext-file como -, el cifrado se escribe en stdout.

El comando encrypt admite la marca opcional --version para indicar la versión de la clave que se debe usar para la desencriptación. Según la configuración predeterminada, se usa la versión principal.

En el siguiente ejemplo de encrypt, se muestra cómo especificar una versión de clave y los datos autenticados adicionales.

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

Protocolo

El contenido que se debe encriptar y que se envía a Cloud KMS en formato JSON debe estar codificado en Base 64. Para obtener más información sobre la codificación y decodificación con Base 64, consulta Codificación Base 64.

Para encriptar los datos, realiza una solicitud POST, proporciona la información del proyecto y la clave que corresponda, y especifica el texto codificado en Base 64 que se encriptará en el campo plaintext del cuerpo de la solicitud. Reemplaza API_KEY por una clave de API válida. Consulta Accede a la API para obtener información sobre cómo generar una clave de 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",
}

En este ejemplo, se usa 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 object Encrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId,
string plaintextFile, string ciphertextFile)
        {
            var cloudKms = CreateAuthorizedClient();
            // Generate the full path of the crypto key to use for encryption.
            var cryptoKey = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}";
            EncryptRequest encryptRequest = new EncryptRequest();
            byte[] plaintext = File.ReadAllBytes(plaintextFile);
            encryptRequest.Plaintext = Convert.ToBase64String(plaintext);
            Console.WriteLine($"dataToEncrypt.Plaintext: {encryptRequest.Plaintext}");
            var result = cloudKms.Projects.Locations.KeyRings.CryptoKeys.Encrypt(name: cryptoKey, body: encryptRequest).Execute();
            // Output encrypted data to a file.
            File.WriteAllBytes(ciphertextFile, Convert.FromBase64String(result.Ciphertext));
            Console.Write($"Encrypted file created: {ciphertextFile}");
            return 0;
        }

Go

func encrypt(projectID, locationID, keyRingID, cryptoKeyID string, plaintext []byte) ([]byte, error) {
	ctx := context.Background()
	client, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return nil, err
	}

	cloudkmsService, err := cloudkms.New(client)
	if err != nil {
		return nil, err
	}

	parentName := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
		projectID, locationID, keyRingID, cryptoKeyID)

	req := &cloudkms.EncryptRequest{
		Plaintext: base64.StdEncoding.EncodeToString(plaintext),
	}
	resp, err := cloudkmsService.Projects.Locations.KeyRings.CryptoKeys.Encrypt(parentName, req).Do()
	if err != nil {
		return nil, err
	}

	return base64.StdEncoding.DecodeString(resp.Ciphertext)
}

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 {
  // The resource name of the cryptoKey
  String resourceName = String.format(
      "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
      projectId, locationId, keyRingId, cryptoKeyId);

  // Create the Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  EncryptRequest request = new EncryptRequest().encodePlaintext(plaintext);
  EncryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
      .encrypt(resourceName, request)
      .execute();

  return response.decodeCiphertext();
}

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

/**
 * Encrypt a text file.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $plaintextFileName The path to the file containing plaintext to encrypt.
 * @param string $ciphertextFileName The path to write the ciphertext.
 * @param string $locationId [optional]
 * @return null
 */
function encrypt($projectId, $keyRingId, $cryptoKeyId, $plaintextFileName, $ciphertextFileName, $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.
    $name = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId
    );

    // Use the KMS API to encrypt the text.
    $encoded = base64_encode(file_get_contents($plaintextFileName));
    $request = new Google_Service_CloudKMS_EncryptRequest();
    $request->setPlaintext($encoded);
    $response = $kms->projects_locations_keyRings_cryptoKeys->encrypt(
        $name,
        $request
    );

    // Write the encrypted text to a file.
    file_put_contents($ciphertextFileName, base64_decode($response['ciphertext']));
    printf('Saved encrypted text to %s' . PHP_EOL, $ciphertextFileName);
}

Python

def encrypt(project_id, location_id, key_ring_id, crypto_key_id,
            plaintext_file_name, ciphertext_file_name):
    """Encrypts data from plaintext_file_name using the provided CryptoKey and
    saves it to ciphertext_file_name so it can only be recovered with a call to
    decrypt.
    """

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the CryptoKey.
    name = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}'.format(
        project_id, location_id, key_ring_id, crypto_key_id)

    # Read data from the input file.
    with io.open(plaintext_file_name, 'rb') as plaintext_file:
        plaintext = plaintext_file.read()

    # Use the KMS API to encrypt the data.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.encrypt(
        name=name,
        body={'plaintext': base64.b64encode(plaintext).decode('ascii')})
    response = request.execute()
    ciphertext = base64.b64decode(response['ciphertext'].encode('ascii'))

    # Write the encrypted data to a file.
    with io.open(ciphertext_file_name, 'wb') as ciphertext_file:
        ciphertext_file.write(ciphertext)

    print('Saved ciphertext to {}.'.format(ciphertext_file_name))

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/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
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}/cryptoKeys/#{crypto_key_id}"

# Read the secret data from the file
plaintext = File.read plaintext_file

request = Cloudkms::EncryptRequest.new plaintext: plaintext

# Use the KMS API to encrypt the data
response = kms_client.encrypt_crypto_key resource, request

# Write the encrypted text to the output file
File.write ciphertext_file, response.ciphertext

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

Inhabilita o programa la destrucción de la versión de clave anterior

Si rotaste la clave en respuesta a una sospecha de incidente, inhabilita o programa la destrucción de la versión de clave anterior después de volver a encriptar los datos.

Inhabilita una versión de clave habilitada

Solo se pueden inhabilitar las claves habilitadas. Para ello, usa el método UpdateCryptoKeyVersion.

Línea de comandos

Para inhabilitar la versión 42 de la clave answer que se encuentra en el llavero de claves answers y en la ubicación global, usa este comando:

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

C#

      public static object DisableCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for disabling the crypto key Version.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}/cryptoKeyVersions/{versionId}";
          // Get crypto key version.
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .CryptoKeyVersionsResource.GetRequest(cloudKms, parent);
          var result = request.Execute();
          result.State = "DISABLED";
          var patchRequest = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .CryptoKeyVersionsResource.PatchRequest(cloudKms, result, parent);
          patchRequest.UpdateMask = "state";
          var patchResult = patchRequest.Execute();
          Console.Write($"Disabled Crypto Key Version: {patchResult.Name}");
          return 0;
      }

Go

func disableCryptoKeyVersion(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.Patch(
		parent, &cloudkms.CryptoKeyVersion{
			State: "DISABLED",
		}).UpdateMask("state").Do()
	if err != nil {
		return err
	}
	log.Print("Disabled crypto key version.")

	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.
  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);

  CryptoKeyVersion newVersionState = new CryptoKeyVersion()
      .setState("DISABLED");

  CryptoKeyVersion response = kms.projects().locations().keyRings().cryptoKeys()
      .cryptoKeyVersions()
      .patch(cryptoKeyVersion, newVersionState)
      .setUpdateMask("state")
      .execute();

  System.out.println(response);
  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

/**
 * Disable a CryptoKey version.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param int $version
 * @param string $locationId [optional]
 * @return null
 */
function disable_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 KeyRing associated with the CryptoKey.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId,
        $version
    );

    // Disable the CryptoKey version.
    $cryptoKeyVersion = $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions
        ->get($parent);
    $cryptoKeyVersion->setState('DISABLED');

    $kms->projects_locations_keyRings_cryptoKeys_cryptoKeyVersions->patch(
        $parent,
        $cryptoKeyVersion,
        ['updateMask' => 'state']
    );

    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.
    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 disable the CryptoKeyVersion.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.cryptoKeyVersions().patch(
        name=name, body={'state': 'DISABLED'}, updateMask='state')
    response = request.execute()

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

# Get a crypto key version
crypto_key_version = kms_client.get_project_location_key_ring_crypto_key_crypto_key_version resource

# Set the primary version state as disabled for update
crypto_key_version.state = "DISABLED"

# Disable the crypto key version
kms_client.patch_project_location_key_ring_crypto_key_crypto_key_version(
  resource,
  crypto_key_version, update_mask: "state"
)

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

Programa la destrucción de una versión de clave

Solo se puede programar la destrucción de las versiones de clave habilitadas o inhabilitadas. Para ello, usa el método DestroyCryptoKeyVersion.

Para evitar accidentes y daños de individuos malintencionados, cuando se usa DestroyCryptoKeyVersion, el material de clave NO se destruye de inmediato. En su lugar, la versión de clave pasa al estado de programada para su destrucción durante 24 horas, período después del cual se destruye automáticamente. No hay forma de anular este resguardo de seguridad. Si decides cancelar la destrucción, tienes un plazo de 24 horas después de la programación para restablecer la versión de clave.

La destrucción se refiere a la eliminación del material de clave, pero aún existe un registro de la versión (p. ej., el número de versión no se puede volver a usar). Esta acción NO se puede revertir, es decir, cualquier dato encriptado con esta versión no podrá recuperarse.

Línea de comandos

Para destruir la versión 42 de la clave answer del llavero de claves answers en la ubicación global}, usa este comando:

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

C#

      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

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

/**
 * 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

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

/**
 * 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

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

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

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...

Documentación de Cloud KMS