키 만들기

이 페이지에서는 Cloud KMS에서 키를 만드는 방법을 보여줍니다. 키는 대칭 또는 비대칭 암호화 키, 비대칭 서명 키이거나 MAC 서명 키일 수 있습니다.

키를 만들 때 특정 Cloud KMS 위치의 키링에 키를 추가합니다. 새 키링을 만들거나 기존 키링을 사용할 수 있습니다. 이 페이지에서는 새 Cloud KMS 또는 Cloud HSM 키를 생성하여 기존 키링에 추가합니다. Cloud EKM 키를 만들려면 외부 키 만들기를 참조하세요. Cloud KMS 또는 Cloud HSM 키를 가져오려면 키 가져오기를 참조하세요.

시작하기 전에

이 페이지의 작업을 완료하려면 먼저 다음 항목이 있어야 합니다.

  1. Cloud KMS 리소스를 포함할 Google Cloud 프로젝트 리소스. 다른 Google Cloud 리소스가 포함되지 않은 Cloud KMS 리소스에 대해 개별 프로젝트를 사용하는 것이 좋습니다.
  2. 키를 만들 키링의 이름과 위치. 다른 리소스 가까이에 있고 원하는 보호 수준을 지원하는 위치에서 키링을 선택합니다. 사용 가능한 위치 및 지원되는 보호 수준을 보려면 Cloud KMS 위치를 참조하세요. 키링을 만들려면 키링 만들기를 참조하세요.
  3. 선택사항: gcloud CLI를 사용하려면 환경을 준비합니다.

    Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

필요한 역할

키를 만드는 데 필요한 권한을 얻으려면 관리자에게 프로젝트 또는 상위 리소스에 대해 다음 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

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

필수 권한

키를 만들려면 다음 권한이 필요합니다.

  • cloudkms.cryptoKeys.create
  • cloudkms.cryptoKeys.get
  • cloudkms.cryptoKeys.list
  • cloudkms.cryptoKeyVersions.create
  • cloudkms.cryptoKeyVersions.get
  • cloudkms.cryptoKeyVersions.list
  • cloudkms.keyRings.get
  • cloudkms.keyRings.list
  • cloudkms.locations.get
  • cloudkms.locations.list
  • resourcemanager.projects.get
  • 공개 키를 가져오려면 다음 안내를 따르세요. cloudkms.cryptoKeyVersions.viewPublicKey
  • 단일 테넌트 HSM 키를 만들려면 다음 단계를 따르세요.
    • cloudkms.singleTenantHsmInstances.get
    • cloudkms.singleTenantHsmInstances.use

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

대칭 암호화 키 만들기

콘솔

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

    Key Management Service로 이동

  2. 키를 만들 키링의 이름을 클릭합니다.

  3. 키 만들기를 클릭합니다.

  4. 키 이름에 키의 이름을 입력합니다.

  5. 보호 수준에서 소프트웨어, HSM 또는 단독 테넌트 HSM을 선택합니다.

  6. 단일 테넌트 HSM을 선택한 경우 키를 만들 단일 테넌트 HSM 인스턴스를 선택합니다.

  7. 키 자료에서 생성된 키를 선택합니다.

  8. 용도에서 Symmetric encrypt/decrypt를 선택합니다.

  9. 순환 주기시작일의 기본값을 그대로 사용합니다.

  10. 만들기를 클릭합니다.

gcloud

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

소프트웨어 또는 멀티 테넌트 Cloud HSM 키를 만들려면 kms keys create 명령어를 사용합니다.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --protection-level "PROTECTION_LEVEL"

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • PROTECTION_LEVEL: 키에 사용할 보호 수준입니다(예: software 또는 hsm). software 키의 --protection-level 플래그는 생략해도 됩니다.

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

단독 테넌트 Cloud HSM 키를 만들려면 kms keys create 명령어에 --crypto-key-backend 플래그를 추가합니다.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --protection-level "hsm-single-tenant" \
    --crypto-key-backend="projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"

다음을 바꿉니다.

  • INSTANCE_PROJECT: 단독 테넌트 Cloud HSM 인스턴스가 있는 프로젝트의 식별자입니다.
  • INSTANCE_NAME: 키를 만들려는 싱글 테넌트 Cloud HSM 인스턴스의 이름입니다. 단독 테넌트 Cloud HSM 인스턴스에 대한 자세한 내용은 단독 테넌트 Cloud HSM 인스턴스 만들기 및 관리를 참고하세요.

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

C#

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


using Google.Cloud.Kms.V1;

public class CreateKeySymmetricEncryptDecryptSample
{
    public CryptoKey CreateKeySymmetricEncryptDecrypt(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-symmetric-encryption-key")
    {
        // 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,
            }
        };

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

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
// on Cloud KMS.
func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-symmetric-encryption-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.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},
		},
	}

	// 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 java.io.IOException;

public class CreateKeySymmetricEncryptDecrypt {

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

  // Create a new key that is used for symmetric encryption and decryption.
  public void createKeySymmetricEncryptDecrypt(
      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);

      // Build the symmetric key to create.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created symmetric 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 id = 'my-symmetric-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 createKeySymmetricEncryptDecrypt() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
      },
    },
  });

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

return createKeySymmetricEncryptDecrypt();

PHP

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

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
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;

function create_key_symmetric_encrypt_decrypt(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-symmetric-key'
): 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)
        );

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

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

from google.cloud import kms


def create_key_symmetric_encrypt_decrypt(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new symmetric encryption/decryption key in Cloud KMS.

    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-symmetric-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,
        },
    }

    # 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 symmetric 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-symmetric-key"

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

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

API

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

소프트웨어 또는 멀티 테넌트 Cloud HSM 키를 만들려면 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": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'

다음을 바꿉니다.

  • PROJECT_ID: 키링이 포함된 프로젝트의 ID입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • KEY_NAME: 키의 이름입니다.
  • PROTECTION_LEVEL: 키의 보호 수준입니다(예: SOFTWARE 또는 HSM).
  • ALGORITHM: HMAC 서명 알고리즘입니다(예: HMAC_SHA256). 지원되는 모든 HMAC 알고리즘을 보려면 HMAC 서명 알고리즘을 참조하세요.
단독 테넌트 Cloud HSM 키를 만들려면 PROTECTION_LEVELHSM_SINGLE_TENANT로 설정하고 kms keys create 명령어에 --crypto-key-backend 플래그를 추가합니다.

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": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "HSM_SINGLE_TENANT",
        "algorithm": "ALGORITHM",
        "crypto-key-backend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME" }}'

다음을 바꿉니다.

  • INSTANCE_PROJECT: 단독 테넌트 Cloud HSM 인스턴스가 있는 프로젝트의 식별자입니다.
  • INSTANCE_NAME: 키를 만들려는 싱글 테넌트 Cloud HSM 인스턴스의 이름입니다. 단독 테넌트 Cloud HSM 인스턴스에 대한 자세한 내용은 단독 테넌트 Cloud HSM 인스턴스 만들기 및 관리를 참고하세요.

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

커스텀 자동 순환으로 대칭 암호화 키 만들기

키를 만들 때 새로운 키 버전이 자동으로 생성되는 간격인 순환 기간을 지정할 수 있습니다. 또한 지금으로부터 하나의 순환 기간 이전 또는 이후에 다음 순환이 발생하도록 다음 순환 시간을 독립적으로 지정할 수도 있습니다.

콘솔

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). 명령어를 실행하는 시점으로부터 하나의 순환 기간 동안 첫 번째 순환을 예약하려면 --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\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
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\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.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    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). 자세한 내용은 CryptoKey.nextRotationTime을 참조하세요.

'폐기 예약됨' 상태 유지 기간 설정

기본적으로 Cloud KMS의 키 버전은 폐기되기 전 30일 동안 폐기 예약됨(DESTROY_SCHEDULED) 상태로 유지됩니다. 폐기 예약됨 상태를 소프트 삭제 상태라고도 합니다. 키 버전이 이 상태로 유지되는 기간을 구성할 수 있으며 다음과 같은 제약이 있습니다.

  • 키를 만드는 도중에만 기간을 설정할 수 있습니다.
  • 키 기간이 지정된 후에는 변경할 수 없습니다.
  • 기간은 이후에 생성되는 모든 키 버전에 적용됩니다.
  • 최소 기간은 모든 키에 대해 24시간이고, 최소 기간이 0인 가져오기 전용 키는 예외입니다.
  • 최대 기간은 120일입니다.
  • 기본 기간은 30일입니다.

조직의 조직 정책에 최소 폐기 예약 기간 값이 정의되었을 수 있습니다. 자세한 내용은 키 폐기 제어를 참조하세요.

폐기 예약 상태에 대해 커스텀 기간을 사용하는 키를 만들려면 다음 단계를 수행합니다.

콘솔

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

    Key Management Service로 이동

  2. 키를 만들 키링의 이름을 클릭합니다.

  3. 키 만들기를 클릭합니다.

  4. 애플리케이션의 키 설정을 구성합니다.

  5. 추가 설정을 클릭합니다.

  6. '폐기 예약됨' 상태 유지 기간에서 영구적으로 폐기되기 전에 키를 폐기 예약됨 상태로 유지할 기간(일)을 선택합니다.

  7. 키 만들기를 클릭합니다.

gcloud

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

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose PURPOSE \
    --destroy-scheduled-duration DURATION

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • PURPOSE: 키의 용도입니다(예: encryption).
  • DURATION: 영구적으로 폐기하기 전에 키를 폐기 예약됨 상태로 유지할 기간입니다.

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

특정 애플리케이션 또는 규제 요구사항에 따라 다른 값이 필요하지 않은 한 모든 키에 대해 기본 기간인 30일을 사용하는 것이 좋습니다.

비대칭 키 만들기

다음 섹션에서는 비대칭 키를 만드는 방법을 보여줍니다.

비대칭 복호화 키 만들기

다음 단계에 따라 지정된 키링 및 위치에 비대칭 복호화 키를 만듭니다. 이러한 예시를 조정하여 다른 보호 수준 또는 알고리즘을 지정할 수 있습니다. 자세한 내용 및 대체 값은 알고리즘보호 수준을 참조하세요.

키를 처음 만들 때 초기 키 버전 상태는 생성 대기 중입니다. 상태가 사용 설정됨으로 바뀌면 키를 사용할 수 있습니다. 키 버전 상태에 대한 자세한 내용은 키 버전 상태를 참조하세요.

콘솔

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

    Key Management Service로 이동

  2. 키를 만들 키링의 이름을 클릭합니다.

  3. 키 만들기를 클릭합니다.

  4. 키 이름에 키의 이름을 입력합니다.

  5. 보호 수준에서 소프트웨어, HSM 또는 단독 테넌트 HSM을 선택합니다.

  6. 단일 테넌트 HSM을 선택한 경우 키를 만들 단일 테넌트 HSM 인스턴스를 선택합니다.

  7. 키 자료에서 생성된 키를 선택합니다.

  8. 용도에서 비대칭 복호화를 선택합니다.

  9. 알고리즘에서 3072비트 RSA - OAEP 패딩 - SHA256 다이제스트를 선택합니다. 이후 키 버전에서 이 값을 변경할 수 있습니다.

  10. 만들기를 클릭합니다.

gcloud

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

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "asymmetric-encryption" \
    --default-algorithm "ALGORITHM" \
    --protection-level "PROTECTION_LEVEL"

다음을 바꿉니다.

  • KEY_NAME: 키의 이름입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.
  • ALGORITHM: 키에 사용할 알고리즘입니다(예: rsa-decrypt-oaep-3072-sha256). 지원되는 비대칭 암호화 알고리즘 목록은 비대칭 암호화 알고리즘을 참조하세요.
  • PROTECTION_LEVEL: 키에 사용할 보호 수준입니다.
단일 테넌트 Cloud HSM 인스턴스에서 키를 만들려면 hsm-single-tenant 보호 수준을 사용하고 --cryptoKeyBackend 플래그를 추가하고 키를 만들려는 단일 테넌트 Cloud HSM 인스턴스의 리소스 식별자를 지정합니다.

--crypto-key-backend "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
모든 플래그 및 가능한 값에 대한 정보를 보려면 `--help` 플래그와 함께 명령어를 실행하세요.

C#

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


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

public class CreateKeyAsymmetricDecryptSample
{
    public CryptoKey CreateKeyAsymmetricDecrypt(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-asymmetric-encrypt-key")
    {
        // 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.AsymmetricDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion