키 순환

이 페이지에서는 자동 또는 수동으로 키를 순환하는 방법을 보여줍니다. 일반적인 키 순환에 대한 자세한 내용은 키 순환을 참조하세요.

필요한 역할

키를 순환하는 데 필요한 권한을 얻으려면 관리자에게 키에 대한 다음의 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 액세스 관리를 참조하세요.

이러한 사전 정의된 역할에는 키를 순환하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.

필수 권한

키를 순환하려면 다음 권한이 필요합니다.

  • 기본 키 버전 변경: cloudkms.cryptoKeys.update
  • 자동 순환 변경 또는 사용 중지: cloudkms.cryptoKeys.update
  • 새 키 버전 만들기: cloudkms.cryptoKeyVersions.create
  • 이전 키 버전 사용 중지: cloudkms.cryptoKeyVersions.update
  • 데이터 다시 암호화:
    • cloudkms.cryptoKeyVersions.useToDecrypt
    • cloudkms.cryptoKeyVersions.useToEncrypt

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

이러한 모든 권한이 포함된 커스텀 역할을 가진 단일 사용자는 스스로 키를 순환하고 데이터를 다시 암호화할 수 있습니다. Cloud KMS 관리자 역할 및 Cloud KMS CryptoKey 암호화/복호화 역할의 사용자는 함께 협력해서 키를 순환하고 데이터를 다시 암호화할 수 있습니다. 역할을 할당할 때 최소 권한의 원칙을 따릅니다. 자세한 내용은 권한 및 역할을 참조하세요.

키를 순환해도 이전 키 버전으로 암호화된 데이터는 자동으로 다시 암호화되지 않습니다. 자세히 알아보려면 복호화 및 다시 암호화를 참조하세요. 키를 암호화해도 기존 키 버전이 자동으로 사용 중지되거나 폐기되지는 않습니다.

자동 순환 구성

새 키를 만들 때 자동 순환을 구성하려면 다음 안내를 따르세요.

콘솔

Google Cloud 콘솔을 사용하여 키를 만들면 Cloud KMS가 순환 기간과 다음 순환 시간을 자동으로 설정합니다. 기본값을 사용하도록 선택하거나 다른 값을 지정할 수 있습니다.

다른 순환 주기와 시작 시간을 지정하려면, 키를 만들만들기 버튼을 클릭하기 전에 다음을 수행합니다.

  1. 키 순환 기간에서 옵션을 선택합니다.

  2. 시작일에서 첫 번째 자동 순환을 실행할 날짜를 선택합니다. 시작일을 기본값으로 설정하여 키를 생성한 시점부터 첫 번째 자동 순환 단일 키 순환 기간을 시작할 수 있습니다.

gcloud

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

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_ROTATION_TIME

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • ROTATION_PERIOD: 키를 순환하는 간격입니다(예: 30d는 키를 30일마다 순환). 순환 기간은 최소 1일에서 최대 100년이어야 합니다. 자세한 내용은 CryptoKey.rotationPeriod를 참조하세요.
  • NEXT_ROTATION_TIME: 첫 번째 순환을 완료할 타임스탬프입니다(예: "2023-01-01T01:02:03"). 명령어를 실행하는 시점으로부터 7일 동안의 첫 번째 순환을 예약하려면 --next-rotation-time을 생략할 수 있습니다. 자세한 내용은 CryptoKey.nextRotationTime을 참조하세요.

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

C#

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


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

public class CreateKeyRotationScheduleSample
{
    public CryptoKey CreateKeyRotationSchedule(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-key-with-rotation-schedule")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            },

            // Rotate the key every 30 days.
            RotationPeriod = new Duration
            {
                Seconds = 60 * 60 * 24 * 30, // 30 days
            },

            // Start the first rotation in 24 hours.
            NextRotationTime = new Timestamp
            {
                Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"time"

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

// createKeyRotationSchedule creates a key with a rotation schedule.
func createKeyRotationSchedule(w io.Writer, parent, id string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-key-with-rotation-schedule"

	// 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.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},

			// Rotate the key every 30 days
			RotationSchedule: &kmspb.CryptoKey_RotationPeriod{
				RotationPeriod: &durationpb.Duration{
					Seconds: int64(60 * 60 * 24 * 30), // 30 days
				},
			},

			// Start the first rotation in 24 hours
			NextRotationTime: &timestamppb.Timestamp{
				Seconds: time.Now().Add(24 * time.Hour).Unix(),
			},
		},
	}

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

Java

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

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.time.temporal.ChronoUnit;

public class CreateKeyRotationSchedule {

  public void createKeyRotationSchedule() 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 id = "my-key";
    createKeyRotationSchedule(projectId, locationId, keyRingId, id);
  }

  // Create a new key that automatically rotates on a schedule.
  public void createKeyRotationSchedule(
      String projectId, String locationId, String keyRingId, String id) 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 parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Calculate the date 24 hours from now (this is used below).
      long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

      // Build the key to create with a rotation schedule.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))

              // Rotate every 30 days.
              .setRotationPeriod(
                  Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))

              // Start the first rotation in 24 hours.
              .setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created key with rotation schedule %s%n", createdKey.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 id = 'my-rotating-encryption-key';

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

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

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyRotationSchedule() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
      },

      // Rotate the key every 30 days.
      rotationPeriod: {
        seconds: 60 * 60 * 24 * 30,
      },

      // Start the first rotation in 24 hours.
      nextRotationTime: {
        seconds: new Date().getTime() / 1000 + 60 * 60 * 24,
      },
    },
  });

  console.log(`Created rotating key: ${key.name}`);
  return key;
}

return createKeyRotationSchedule();

PHP

이 코드를 실행하려면 먼저 Google Cloud에서 PHP 사용에 관해 알아보고 Cloud KMS PHP SDK 설치하세요.

use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

function create_key_rotation_schedule(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-key-with-rotation-schedule'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION))

        // Rotate the key every 30 days.
        ->setRotationPeriod((new Duration())
            ->setSeconds(60 * 60 * 24 * 30)
        )

        // Start the first rotation in 24 hours.
        ->setNextRotationTime((new Timestamp())
            ->setSeconds(time() + 60 * 60 * 24)
        );

    // Call the API.
    $createdKey = $client->createCryptoKey($keyRingName, $id, $key);
    printf('Created key with rotation: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

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

import time

from google.cloud import kms

def create_key_rotation_schedule(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new key in Cloud KMS that automatically rotates.

    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 create (e.g. 'my-rotating-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

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

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    algorithm = (
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
    )
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
        # Rotate the key every 30 days.
        "rotation_period": {"seconds": 60 * 60 * 24 * 30},
        # Start the first rotation in 24 hours.
        "next_rotation_time": {"seconds": int(time.time()) + 60 * 60 * 24},
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created labeled key: {created_key.name}")
    return created_key

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"
# id          = "my-key-with-rotation"

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

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

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:            :ENCRYPT_DECRYPT,
  version_template:   {
    algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
  },

  # Rotate the key every 30 days.
  rotation_period:    {
    seconds: 60 * 60 * 24 * 30
  },

  # Start the first rotation in 24 hours.
  next_rotation_time: {
    seconds: (Time.now + (60 * 60 * 24)).to_i
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created rotating key: #{created_key.name}"

API

이 예시에서는 curl을 HTTP 클라이언트로 사용하여 API 사용을 보여줍니다. 액세스 제어에 대한 자세한 내용은 Cloud KMS API 액세스를 참조하세요.

키를 만들려면 CryptoKey.create 메서드를 사용합니다.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "PURPOSE", "rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'

다음을 바꿉니다.

  • PURPOSE: 키의 용도입니다.
  • ROTATION_PERIOD: 키를 순환하는 간격입니다(예: 30d는 키를 30일마다 순환). 순환 기간은 최소 1일에서 최대 100년이어야 합니다. 자세한 내용은 CryptoKey.rotationPeriod를 참조하세요.
  • NEXT_ROTATION_TIME: 첫 번째 순환을 완료할 타임스탬프입니다(예: "2023-01-01T01:02:03"). 명령어를 실행하는 시점으로부터 7일 동안의 첫 번째 순환을 예약하려면 --next-rotation-time을 생략할 수 있습니다. 자세한 내용은 CryptoKey.nextRotationTime을 참조하세요.

기존 키에서 자동 순환을 구성하려면 다음 안내를 따르세요.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 순환 일정을 추가할 키가 포함 된 키링의 이름을 클릭합니다.

  3. 순환 일정을 추가할 키를 클릭합니다.

  4. 헤더에서 순환 주기 수정을 클릭합니다.

  5. 프롬프트에서 순환 주기시작일 입력란에 새 값을 선택합니다.

  6. 프롬프트에서 저장을 클릭합니다.

gcloud

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

gcloud kms keys update KEY_NAME \
    --location LOCATION \
    --keyring KEY_RING \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_ROTATION_TIME

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • ROTATION_PERIOD: 키를 순환하는 간격입니다(예: 30d는 키를 30일마다 순환). 순환 기간은 최소 1일에서 최대 100년이어야 합니다. 자세한 내용은 CryptoKey.rotationPeriod를 참조하세요.
  • NEXT_ROTATION_TIME: 첫 번째 순환을 완료할 타임스탬프입니다(예: "2023-01-01T01:02:03"). 명령어를 실행하는 시점으로부터 7일 동안의 첫 번째 순환을 예약하려면 --next-rotation-time을 생략할 수 있습니다. 자세한 내용은 CryptoKey.nextRotationTime을 참조하세요.

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

C#

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


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

public class UpdateKeyAddRotationSample
{
    public CryptoKey UpdateKeyAddRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            // Provide the name of the key to update.
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),

            // Rotate the key every 30 days.
            RotationPeriod = new Duration
            {
                Seconds = 60 * 60 * 24 * 30, // 30 days
            },

            // Start the first rotation in 24 hours.
            NextRotationTime = new Timestamp
            {
                Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
            }
        };

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

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        return result;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"time"

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

// addRotationSchedule updates a key to add a rotation schedule. If the key
// already has a rotation schedule, it is overwritten.
func addRotationSchedule(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"

	// 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.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			// Provide the name of the key to update
			Name: name,

			// Rotate the key every 30 days
			RotationSchedule: &kmspb.CryptoKey_RotationPeriod{
				RotationPeriod: &durationpb.Duration{
					Seconds: int64(60 * 60 * 24 * 30), // 30 days
				},
			},

			// Start the first rotation in 24 hours
			NextRotationTime: &timestamppb.Timestamp{
				Seconds: time.Now().Add(24 * time.Hour).Unix(),
			},
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"rotation_period", "next_rotation_time"},
		},
	}

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

Java

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

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;
import java.time.temporal.ChronoUnit;

public class UpdateKeyAddRotation {

  public void updateKeyAddRotation() 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";
    updateKeyAddRotation(projectId, locationId, keyRingId, keyId);
  }

  // Update a key to add or change a rotation schedule.
  public void updateKeyAddRotation(
      String projectId, String locationId, String keyRingId, String keyId) 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 name from the project, location, and key ring.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Calculate the date 24 hours from now (this is used below).
      long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

      // Build the key to update with a rotation schedule.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setName(cryptoKeyName.toString())
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))

              // Rotate every 30 days.
              .setRotationPeriod(
                  Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))

              // Start the first rotation in 24 hours.
              .setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
              .build();

      // Construct the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

      // Update the key.
      CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated key %s%n", updatedKey.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 name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyAddRotation() {
  const [key] = await client.updateCryptoKey({
    cryptoKey: {
      name: keyName,

      // Rotate the key every 30 days.
      rotationPeriod: {
        seconds: 60 * 60 * 24 * 30,
      },

      // Start the first rotation in 24 hours.
      nextRotationTime: {
        seconds: new Date().getTime() / 1000 + 60 * 60 * 24,
      },
    },
    updateMask: {
      paths: ['rotation_period', 'next_rotation_time'],
    },
  });

  console.log(`Updated rotation for: ${key.name}`);
  return key;
}

return updateKeyAddRotation();

PHP

이 코드를 실행하려면 먼저 Google Cloud에서 PHP 사용에 관해 알아보고 Cloud KMS PHP SDK 설치하세요.

use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Protobuf\Duration;
use Google\Protobuf\FieldMask;
use Google\Protobuf\Timestamp;

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

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key.
    $key = (new CryptoKey())
        ->setName($keyName)

        // Rotate the key every 30 days.
        ->setRotationPeriod((new Duration())
            ->setSeconds(60 * 60 * 24 * 30)
        )

        // Start the first rotation in 24 hours.
        ->setNextRotationTime((new Timestamp())
            ->setSeconds(time() + 60 * 60 * 24)
        );

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

    // Call the API.
    $updatedKey = $client->updateCryptoKey($key, $updateMask);
    printf('Updated key: %s' . PHP_EOL, $updatedKey->getName());

    return $updatedKey;
}

Python

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

import time

from google.cloud import kms

def update_key_add_rotation(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Add a rotation schedule to an existing 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').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

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

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    key = {
        "name": key_name,
        "rotation_period": {
            "seconds": 60 * 60 * 24 * 30  # Rotate the key every 30 days.
        },
        "next_rotation_time": {
            "seconds": int(time.time())
            + 60 * 60 * 24  # Start the first rotation in 24 hours.
        },
    }

    # Build the update mask.
    update_mask = {"paths": ["rotation_period", "next_rotation_time"]}

    # Call the API.
    updated_key = client.update_crypto_key(
        request={"crypto_key": key, "update_mask": update_mask}
    )
    print(f"Updated key: {updated_key.name}")
    return updated_key

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"

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

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

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the key.
key = {
  name:               key_name,

  # Rotate the key every 30 days.
  rotation_period:    {
    seconds: 60 * 60 * 24 * 30
  },

  # Start the first rotation in 24 hours.
  next_rotation_time: {
    seconds: (Time.now + (60 * 60 * 24)).to_i
  }
}

# Build the field mask.
update_mask = { paths: ["rotation_period", "next_rotation_time"] }

# Call the API.
updated_key = client.update_crypto_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_key.name}"

API

이 예시에서는 curl을 HTTP 클라이언트로 사용하여 API 사용을 보여줍니다. 액세스 제어에 대한 자세한 내용은 Cloud KMS API 액세스를 참조하세요.

키를 업데이트하려면 CryptoKey.patch 메서드를 사용합니다.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \
    --request "PATCH" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'

다음을 바꿉니다.

  • ROTATION_PERIOD: 키를 순환하는 간격입니다(예: 30d는 키를 30일마다 순환). 순환 기간은 최소 1일에서 최대 100년이어야 합니다. 자세한 내용은 CryptoKey.rotationPeriod를 참조하세요.
  • NEXT_ROTATION_TIME: 첫 번째 순환을 완료할 타임스탬프입니다(예: "2023-01-01T01:02:03"). 명령어를 실행하는 시점으로부터 7일 동안의 첫 번째 순환을 예약하려면 --next-rotation-time을 생략할 수 있습니다. 자세한 내용은 CryptoKey.nextRotationTime을 참조하세요.

수동으로 키 순환

먼저 새 키 버전을 만듭니다.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 새 키 버전을 만들 키가 포함된 키링의 이름을 클릭합니다.

  3. 새 키 버전을 만들 키를 클릭합니다.

  4. 헤더에서 순환을 클릭합니다.

  5. 표시되는 메시지에서 순환을 클릭하여 확인합니다.

gcloud

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

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.

키 버전은 번호가 순차적으로 지정됩니다.

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

C#

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


using Google.Cloud.Kms.V1;

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

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

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion { };

        // Call the API.
        CryptoKeyVersion result = client.CreateCryptoKeyVersion(keyName, keyVersion);

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

// createKeyVersion creates a new key version for the given key.
func createKeyVersion(w io.Writer, parent string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"

	// 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.CreateCryptoKeyVersionRequest{
		Parent: parent,
	}

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

Java

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

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class CreateKeyVersion {

  public void createKeyVersion() 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";
    createKeyVersion(projectId, locationId, keyRingId, keyId);
  }

  // Create a new key version.
  public void createKeyVersion(String projectId, String locationId, String keyRingId, String keyId)
      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 parent name from the project, location, and key ring.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build the key version to create.
      CryptoKeyVersion keyVersion = CryptoKeyVersion.newBuilder().build();

      // Create the key.
      CryptoKeyVersion createdVersion = client.createCryptoKeyVersion(cryptoKeyName, keyVersion);
      System.out.printf("Created key version %s%n", createdVersion.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';

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

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

// Build the parent key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function createKeyVersion() {
  const [version] = await client.createCryptoKeyVersion({
    parent: keyName,
  });

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

return createKeyVersion();

PHP

이 코드를 실행하려면 먼저 Google Cloud에서 PHP 사용에 관해 알아보고 Cloud KMS PHP SDK 설치하세요.

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

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

    // Build the parent key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key version.
    $version = new CryptoKeyVersion();

    // Call the API.
    $createdVersion = $client->createCryptoKeyVersion($keyName, $version);
    printf('Created key version: %s' . PHP_EOL, $createdVersion->getName());

    return $createdVersion;
}

Python

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

from google.cloud import kms

def create_key_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new version of the given 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 for which to create a new version (e.g. 'my-key').

    Returns:
        CryptoKeyVersion: Cloud KMS key version.

    """

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

    # Build the parent key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # Build the key version.
    version = {}

    # Call the API.
    created_version = client.create_crypto_key_version(
        request={"parent": key_name, "crypto_key_version": version}
    )
    print(f"Created key version: {created_version.name}")
    return created_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"

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

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

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the version.
version = {}

# Call the API.
created_version = client.create_crypto_key_version parent: key_name, crypto_key_version: version
puts "Created key version: #{created_version.name}"

API

이 예시에서는 curl을 HTTP 클라이언트로 사용하여 API 사용을 보여줍니다. 액세스 제어에 대한 자세한 내용은 Cloud KMS API 액세스를 참조하세요.

키를 수동으로 순환하려면 먼저 CryptoKeyVersions.create 메서드를 호출하여 새 키 버전을 만듭니다.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions" \
    --request "POST" \
    --header "authorization: Bearer TOKEN"

이 명령어는 새 키 버전을 생성하지만, 기본 버전으로 설정되지는 않습니다.

새 키 버전을 기본 버전으로 설정하려면 기존 버전을 기본 키 버전으로 설정을 참조하세요.

필요한 경우 이전 키 버전을 사용하여 암호화된 데이터를 다시 암호화합니다.

기존 버전을 기본 키 버전으로 설정

다른 키 버전을 키의 기본 버전으로 설정하려면 새 기본 버전 정보로 키를 업데이트합니다. 기본 버전으로 구성하려면 먼저 키 버전을 사용 설정해야 합니다.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 기본 버전을 업데이트할 키가 포함된 키링의 이름을 클릭합니다.

  3. 기본 버전을 업데이트할 키를 클릭합니다.

  4. 기본값으로 지정하려는 키 버전에 해당하는 행에서 더보기를 클릭합니다.

  5. 메뉴에서 기본 버전으로 설정을 클릭합니다.

  6. 확인 대화상자가 표시되면 기본으로 설정을 클릭합니다.

gcloud

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

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --primary-version KEY_VERSION

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • KEY_VERSION: 새 기본 키 버전의 버전 번호입니다.

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

C#

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


using Google.Cloud.Kms.V1;

public class UpdateKeySetPrimarySample
{
    public CryptoKey UpdateKeySetPrimary(
      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 name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Call the API.
        CryptoKey result = client.UpdateCryptoKeyPrimaryVersion(keyName, keyVersionId);

        // Return the updated key.
        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"
)

// updateKeySetPrimary updates the primary key version on a Cloud KMS key.
func updateKeySetPrimary(w io.Writer, name, version string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"
	// version := "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.UpdateCryptoKeyPrimaryVersionRequest{
		Name:               name,
		CryptoKeyVersionId: version,
	}

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

	return nil
}

Java

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

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class UpdateKeySetPrimary {

  public void updateKeySetPrimary() 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";
    updateKeySetPrimary(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Update a key's primary version.
  public void updateKeySetPrimary(
      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 name from the project, location, key ring, and keyId.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Create the key.
      CryptoKey createdKey = client.updateCryptoKeyPrimaryVersion(cryptoKeyName, keyVersionId);
      System.out.printf("Updated key primary version %s%n", createdKey.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 name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeySetPrimary() {
  const [key] = await client.updateCryptoKeyPrimaryVersion({
    name: keyName,
    cryptoKeyVersionId: versionId,
  });

  console.log(`Set primary to ${versionId}`);
  return key;
}

return updateKeySetPrimary();

PHP

이 코드를 실행하려면 먼저 Google Cloud에서 PHP 사용에 관해 알아보고 Cloud KMS PHP SDK 설치하세요.

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

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

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Call the API.
    $updatedKey = $client->updateCryptoKeyPrimaryVersion($keyName, $versionId);
    printf('Updated primary %s to %s' . PHP_EOL, $updatedKey->getName(), $versionId);

    return $updatedKey;
}

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 parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Call the API.
updated_key = client.update_crypto_key_primary_version name: key_name, crypto_key_version_id: version_id
puts "Updated primary #{updated_key.name} to #{version_id}"

Python

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

from google.cloud import kms

def update_key_set_primary(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.CryptoKey:
    """
    Update the primary version of 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 to make primary (e.g. '2').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

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

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # Call the API.
    updated_key = client.update_crypto_key_primary_version(
        request={"name": key_name, "crypto_key_version_id": version_id}
    )
    print(f"Updated {updated_key.name} primary to {version_id}")
    return updated_key

API

이 예시에서는 curl을 HTTP 클라이언트로 사용하여 API 사용을 보여줍니다. 액세스 제어에 대한 자세한 내용은 Cloud KMS API 액세스를 참조하세요.

CryptoKey.updatePrimaryVersion 메서드를 호출하여 기본 키 버전을 변경합니다.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME:updatePrimaryVersion" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"cryptoKeyVersionId": "KEY_VERSION"}'

다음을 바꿉니다.

  • PROJECT_ID: 키링이 포함된 프로젝트의 ID입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • KEY_NAME: 키의 이름입니다.
  • KEY_VERSION: 새 기본 키 버전의 버전 번호입니다.

기본 키 버전을 변경하면 일반적으로 변경사항이 1분 이내에 일관성을 갖습니다. 하지만 예외적인 경우에 이 변경사항이 전파되는 데 최대 3시간이 걸릴 수 있습니다. 이 시간 중에는 이전 기본 버전이 데이터를 암호화하는 데 사용될 수 있습니다. 자세한 내용은 Cloud KMS 리소스 일관성을 참조하세요.

자동 순환 사용 중지

키 자동 순환을 사용 중지하려면 키의 순환 일정을 삭제합니다.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 순환 일정을 삭제할 키가 포함 된 키링의 이름을 클릭합니다.

  3. 순환 일정을 삭제할 키를 클릭합니다.

  4. 헤더에서 순환 주기 수정을 클릭합니다.

  5. 프롬프트에서 순환 주기 필드를 클릭하고 사용 안함(수동 순환)을 선택합니다.

  6. 프롬프트에서 저장을 클릭합니다.

gcloud

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

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --remove-rotation-schedule

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.

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

C#

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


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

public class UpdateKeyRemoveRotationSample
{
    public CryptoKey UpdateKeyRemoveRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),
            RotationPeriod = null,
            NextRotationTime = null,
        };

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

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        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"
)

// removeRotationSchedule updates a key to remove a rotation schedule, if one
// exists.
func removeRotationSchedule(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"

	// 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.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			// Provide the name of the key to update
			Name: name,

			// Remove any rotation fields.
			RotationSchedule: nil,
			NextRotationTime: nil,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"rotation_period", "next_rotation_time"},
		},
	}

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

Java

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

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateKeyRemoveRotation {

  public void updateKeyRemoveRotation() 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";
    updateKeyRemoveRotation(projectId, locationId, keyRingId, keyId);
  }

  // Update a key to remove all labels.
  public void updateKeyRemoveRotation(
      String projectId, String locationId, String keyRingId, String keyId) 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 name from the project, location, key ring, and keyId.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build an empty key with no labels.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setName(cryptoKeyName.toString())
              .clearRotationPeriod()
              .clearNextRotationTime()
              .build();

      // Construct the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

      // Create the key.
      CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated key %s%n", createdKey.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';

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

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

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyRemoveRotation() {
  const [key] = await client.updateCryptoKey({
    cryptoKey: {
      name: keyName,
      rotationPeriod: null,
      nextRotationTime: null,
    },
    updateMask: {
      paths: ['rotation_period', 'next_rotation_time'],
    },
  });

  console.log(`Removed rotation for: ${key.name}`);
  return key;
}

return updateKeyRemoveRotation();

PHP

이 코드를 실행하려면 먼저 Google Cloud에서 PHP 사용에 관해 알아보고 Cloud KMS PHP SDK 설치하세요.

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

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

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key.
    $key = (new CryptoKey())
        ->setName($keyName);

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

    // Call the API.
    $updatedKey = $client->updateCryptoKey($key, $updateMask);
    printf('Updated key: %s' . PHP_EOL, $updatedKey->getName());

    return $updatedKey;
}

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"

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

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

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the key.
key = {
  name:               key_name,
  rotation_period:    nil,
  next_rotation_time: nil
}

# Build the field mask.
update_mask = { paths: ["rotation_period", "next_rotation_time"] }

# Call the API.
updated_key = client.update_crypto_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_key.name}"

Python

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

from google.cloud import kms

def update_key_remove_rotation(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Remove a rotation schedule from an existing 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').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

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

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    key = {"name": key_name}

    # Build the update mask.
    update_mask = {"paths": ["rotation_period", "next_rotation_time"]}

    # Call the API.
    updated_key = client.update_crypto_key(
        request={"crypto_key": key, "update_mask": update_mask}
    )
    print(f"Updated key: {updated_key.name}")
    return updated_key

API

이 예시에서는 curl을 HTTP 클라이언트로 사용하여 API 사용을 보여줍니다. 액세스 제어에 대한 자세한 내용은 Cloud KMS API 액세스를 참조하세요.

키를 업데이트하려면 CryptoKey.patch 메서드를 사용합니다.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \
    --request "PATCH" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"rotationPeriod": null, "nextRotationTime": null}'

rotationPeriodnextRotationTime에 대한 자세한 내용은 keyRings.cryptoKeys를 참조하세요.

외부 키 순환

조정된 외부 키 순환

대칭 좌표 외부 키의 자동 순환을 구성할 수 있습니다. 대칭 또는 비대칭 좌표 외부 키의 새 키 버전을 수동으로 만들 수도 있습니다.

새 키 버전을 순환하거나 만들면 해당 키로 보호되는 모든 새로 생성되는 데이터가 새로운 키 버전을 사용해서 암호화됩니다. 이전 키 버전으로 보호되는 데이터는 다시 암호화되지 않습니다. 따라서 외부 키 관리자가 이전 키 버전의 키 자료를 계속 사용할 수 있게 해야 합니다.

조정된 외부 키의 새 키 버전을 만들려면 다음 단계를 완료하세요.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리로 이동

  2. 키 링을 선택한 다음 키를 선택합니다.

  3. 버전 만들기를 클릭합니다. Cloud KMS와 EKM 모두에서 새 키 버전이 생성된다는 메시지가 표시됩니다. 키 경로 또는 키 URI 필드가 표시되면 선택한 키는 조정된 외부 키가 아닙니다.

  4. 새 키 버전을 만들 것인지 확인하려면 버전 만들기를 클릭합니다.

새 키 버전이 생성 대기 중 상태로 표시됩니다. 대칭 키의 경우 수동으로 생성된 키 버전이 기본 키 버전으로 자동 설정되지 않습니다. 새 키 버전을 기본 버전으로 설정할 수 있습니다.

gcloud CLI

새 대칭 키 버전을 만들고 기본 키 버전으로 설정하려면 kms keys versions create 명령어를 --primary 플래그와 함께 사용합니다.

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --primary

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.

새로운 비대칭 키 버전을 만들거나 기본 키 버전이 아닌 새 대칭 키 버전을 만들려면 kms keys versions create 명령어를 사용합니다.

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.

VPC 키를 통해 수동으로 관리되는 Cloud EKM 순환

먼저 외부 키 관리자에서 외부 키 자료를 순환합니다. 그 결과 새 키 경로가 발생하면 새 Cloud EKM 키 버전을 순환하거나 새 키 경로로 만들어야 합니다. 대칭 암호화 키의 경우 Cloud EKM 키를 순환하고 외부 키 관리자에서 새 키 경로를 지정합니다. 비대칭 키의 경우 새 키 버전을 만들고 새 키 경로를 지정합니다.

새 키 버전을 순환하거나 만들면 해당 키로 보호되는 모든 새로 생성되는 데이터가 새로운 키 버전을 사용해서 암호화됩니다. 이전 키 버전으로 보호되는 데이터는 다시 암호화되지 않습니다. 따라서 외부 키 관리자가 이전 키 버전의 키 자료를 계속 사용할 수 있게 해야 합니다.

외부 키 관리 파트너 시스템의 키 자료는 변경되지 않았으나 키 경로가 변경된 경우에는 키를 순환할 필요 없이 키의 외부 경로를 업데이트하면 됩니다.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리로 이동

  2. 키 링을 선택한 다음 키를 선택합니다.

  3. 키 순환을 클릭합니다.

  4. 키 경로에 새 버전의 키 경로를 입력합니다.

  5. 키 순환을 클릭하여 확인합니다.

gcloud

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

새 대칭 키 버전을 만들고 기본 키 버전으로 설정하려면 kms keys versions create 명령어를 --primary 플래그와 함께 사용합니다.

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --ekm-connection-key-path EXTERNAL_KEY_PATH \
    --primary

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • EXTERNAL_KEY_PATH: 새 외부 키 버전의 경로입니다.

새로운 비대칭 키 버전을 만들거나 기본 키 버전이 아닌 새 대칭 키 버전을 만들려면 kms keys versions create 명령어를 사용합니다.

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --ekm-connection-key-path EXTERNAL_KEY_PATH

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • EXTERNAL_KEY_PATH: 새 외부 키 버전의 경로입니다.

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

키 버전이 성공적으로 생성되면 다른 Cloud KMS 키 버전을 사용할 때처럼 사용하면 됩니다.

인터넷 키를 통해 수동으로 관리되는 Cloud EKM 순환

먼저 외부 키 관리자에서 외부 키 자료를 순환합니다. 그 결과 새 URI가 발생하면 새 Cloud EKM 키 버전을 순환하거나 새 URI로 만들어야 합니다. 대칭 암호화 키의 경우 Cloud EKM 키를 순환하고 외부 키 관리자에서 새 키 URI를 지정합니다. 비대칭 키의 경우 새 키 버전을 만들고 새 키 URI를 지정합니다.

새 키 버전을 순환하거나 만들면 해당 키로 보호되는 모든 새로 생성되는 데이터가 새로운 키 버전을 사용해서 암호화됩니다. 이전 키 버전으로 보호되는 데이터는 다시 암호화되지 않습니다. 따라서 외부 키 관리자가 이전 키 버전의 키 자료를 계속 사용할 수 있게 해야 합니다.

외부 키 관리 파트너 시스템의 키 자료는 변경되지 않지만 URI가 변경되면 키를 순환하지 않고도 키의 외부 URI를 업데이트할 수 있습니다.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리로 이동

  2. 키 링을 선택한 다음 키를 선택합니다.

  3. 대칭 키의 경우 키 순환을 선택하거나 비대칭 키의 경우 버전 만들기를 선택하세요.

  4. 새 키 URI를 입력한 후 대칭 키에 대해 키 순환을 선택하고 비대칭 키에 대해서는 버전 만들기를 선택합니다.

새 키 버전이 기본 버전이 됩니다.

gcloud CLI

새 대칭 키 버전을 만들고 기본 키 버전으로 설정하려면 kms keys versions create 명령어를 --primary 플래그와 함께 사용합니다.

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --external-key-uri EXTERNAL_KEY_URI \
  --primary

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • EXTERNAL_KEY_URI: 새 외부 키 버전의 키 URI입니다.

새로운 비대칭 키 버전을 만들거나 기본 키 버전이 아닌 새 대칭 키 버전을 만들려면 kms keys versions create 명령어를 사용합니다.

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --external-key-uri EXTERNAL_KEY_URI

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • EXTERNAL_KEY_URI: 새 외부 키 버전의 키 URI입니다.