데이터 재암호화

이 주제에서는 Cloud Key Management Service 대칭 키를 사용하여 데이터를 다시 암호화하는 방법을 보여줍니다. 비대칭 키에 이러한 예를 적용할 수 있습니다. 키의 무단 사용이 의심되는 경우 해당 키로 보호되는 데이터를 다시 암호화한 다음 이전 키 버전을 사용 중지하거나 폐기 예약해야 합니다.

시작하기 전에

이 시나리오에는 다음 조건이 필요합니다.

  • Cloud KMS를 사용하여 이미 데이터를 암호화한 상태입니다.

  • 암호화에 사용되는 키 버전이 사용 중지됨, 폐기 예약됨 또는 폐기됨 상태가 아닙니다. 이 키 버전을 사용하여 암호화된 데이터를 복호화합니다.

  • 이미 키 순환을 완료한 상태입니다. 키 순환은 새로운 기본 키 버전을 만듭니다. 새로운 기본 키 버전을 사용하여 데이터를 다시 암호화합니다.

비대칭 키를 사용하여 데이터 재암호화

이 주제의 예는 대칭 키를 사용하여 데이터를 다시 암호화하는 방법을 보여줍니다. 대칭 키를 사용하면 Cloud KMS가 자동으로 복호화에 사용할 키 버전을 추론합니다. 비대칭 키를 사용할 때는 키 버전을 지정해야 합니다.

비대칭 키로 데이터를 다시 암호화하는 워크플로는 이 주제에 설명된 것과 유사합니다.

데이터 워크플로 다시 암호화

데이터를 다시 암호화하고 원래 암호화에 사용된 키 버전을 사용 중지하거나 폐기 예약하려면 다음 단계를 따르세요.

  1. 이전 키 버전을 사용하여 데이터 복호화

  2. 새로운 기본 키 버전을 사용하여 데이터 다시 암호화

  3. 이전 키 버전을 중지 또는 폐기 예약

이전 키 버전을 사용하여 데이터 복호화

키 버전이 '사용 중지됨', '폐기 예약됨' 또는 '폐기됨' 상태가 아닌 한 Cloud KMS에서 자동으로 올바른 키 버전을 사용하여 데이터를 복호화합니다. 다음 예는 데이터를 복호화하는 방법을 보여줍니다. 이 코드는 암호화 및 복호화에 사용된 것과 동일한 복호화 코드입니다.

gcloud

명령줄에서 Cloud KMS를 사용하려면 먼저 최신 버전의 Google Cloud CLI로 설치 또는 업그레이드하세요.

gcloud kms decrypt \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION  \
    --ciphertext-file FILE_TO_DECRYPT \
    --plaintext-file DECRYPTED_OUTPUT

다음을 바꿉니다.

  • KEY_NAME: 복호화에 사용할 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링이 포함된 Cloud KMS 위치입니다.
  • FILE_TO_DECRYPT: 복호화하려는 파일의 경로입니다.
  • DECRYPTED_OUTPUT: 복호화된 출력을 저장할 경로입니다.

모든 플래그 및 가능한 값에 대한 정보를 보려면 --help 플래그와 함께 명령어를 실행하세요.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 Cloud KMS C# SDK를 설치합니다.


using Google.Cloud.Kms.V1;
using Google.Protobuf;
using System.Text;

public class DecryptSymmetricSample
{
    public string DecryptSymmetric(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key",
      byte[] ciphertext = null)
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Call the API.
        DecryptResponse result = client.Decrypt(keyName, ByteString.CopyFrom(ciphertext));

        // Get the plaintext. Cryptographic plaintexts and ciphertexts are
        // always byte arrays.
        byte[] plaintext = result.Plaintext.ToByteArray();

        // Return the result.
        return Encoding.UTF8.GetString(plaintext);
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 Cloud KMS Go SDK를 설치합니다.

import (
	"context"
	"fmt"
	"hash/crc32"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

// decryptSymmetric will decrypt the input ciphertext bytes using the specified symmetric key.
func decryptSymmetric(w io.Writer, name string, ciphertext []byte) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"
	// ciphertext := []byte("...")  // result of a symmetric encryption call

	// 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()

	// Optional, but recommended: Compute ciphertext's CRC32C.
	crc32c := func(data []byte) uint32 {
		t := crc32.MakeTable(crc32.Castagnoli)
		return crc32.Checksum(data, t)
	}
	ciphertextCRC32C := crc32c(ciphertext)

	// Build the request.
	req := &kmspb.DecryptRequest{
		Name:             name,
		Ciphertext:       ciphertext,
		CiphertextCrc32C: wrapperspb.Int64(int64(ciphertextCRC32C)),
	}

	// Call the API.
	result, err := client.Decrypt(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to decrypt ciphertext: %w", err)
	}

	// Optional, but recommended: perform integrity verification on result.
	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
	// https://cloud.google.com/kms/docs/data-integrity-guidelines
	if int64(crc32c(result.Plaintext)) != result.PlaintextCrc32C.Value {
		return fmt.Errorf("Decrypt: response corrupted in-transit")
	}

	fmt.Fprintf(w, "Decrypted plaintext: %s", result.Plaintext)
	return nil
}

Java

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 Cloud KMS 자바 SDK를 설치합니다.

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.DecryptResponse;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class DecryptSymmetric {

  public void decryptSymmetric() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId =