Cloud HSM

이 문서에서는 Cloud HSM의 개요와 Cloud Key Management Service에서 HSM으로 보호되는 암호화 키를 만들고 사용하는 방법을 설명합니다.

Cloud HSM이란 무엇인가요?

Cloud HSM은 클라우드에 호스팅되는 하드웨어 보안 모듈 (HSM) 서비스로, 이 서비스를 사용하면 FIPS 140-2 Level 3 인증 HSM 클러스터에서 암호화 키를 호스팅하고 암호화 작업을 수행할 수 있습니다. Google이 HSM 클러스터를 관리하므로 개발자는 클러스터링, 확장 또는 패치 적용에 신경쓰지 않아도 됩니다. Cloud HSM은 프런트엔드로 Cloud KMS를 사용하므로 개발자는 Cloud KMS가 제공하는 모든 편의성 및 기능을 활용할 수 있습니다.

키링 만들기

키를 만들 때 특정 Google Cloud 위치의 키링에 키를 추가합니다. 새 키링을 만들거나 기존 키링을 사용할 수 있습니다. 이 주제에서는 새 키링을 만들고 거기에 새 키를 추가합니다.

Cloud HSM을 지원하는 Google Cloud 위치에 키링을 만듭니다.

콘솔

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

    Key Management Service로 이동

  2. 키링 만들기를 클릭합니다.

  3. 키링 이름에 키링 이름을 입력합니다.

  4. 키링 위치에서 "us-east1"과 같은 위치를 선택합니다.

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

gcloud

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

    Cloud Shell 활성화

  2. 환경에서 gcloud kms keyrings create 명령어를 실행합니다.

    gcloud kms keyrings create KEY_RING \
        --location LOCATION
    

    다음을 바꿉니다.

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

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

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Kms.V1;

public class CreateKeyRingSample
{
    public KeyRing CreateKeyRing(
      string projectId = "my-project", string locationId = "us-east1",
      string id = "my-key-ring")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent location name.
        LocationName locationName = new LocationName(projectId, locationId);

        // Build the key ring.
        KeyRing keyRing = new KeyRing { };

        // Call the API.
        KeyRing result = client.CreateKeyRing(locationName, id, keyRing);

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

// createKeyRing creates a new ring to store keys on KMS.
func createKeyRing(w io.Writer, parent, id string) error {
	// parent := "projects/PROJECT_ID/locations/global"
	// id := "my-key-ring"

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

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

Java

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

import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;
import java.io.IOException;

public class CreateKeyRing {

  public void createKeyRing() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String id = "my-asymmetric-signing-key";
    createKeyRing(projectId, locationId, id);
  }

  // Create a new key ring.
  public void createKeyRing(String projectId, String locationId, 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 and location.
      LocationName locationName = LocationName.of(projectId, locationId);

      // Build the key ring to create.
      KeyRing keyRing = KeyRing.newBuilder().build();

      // Create the key ring.
      KeyRing createdKeyRing = client.createKeyRing(locationName, id, keyRing);
      System.out.printf("Created key ring %s%n", createdKeyRing.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 id = 'my-key-ring';

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

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

// Build the parent location name
const locationName = client.locationPath(projectId, locationId);

async function createKeyRing() {
  const [keyRing] = await client.createKeyRing({
    parent: locationName,
    keyRingId: id,
  });

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

return createKeyRing();

PHP

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

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateKeyRingRequest;
use Google\Cloud\Kms\V1\KeyRing;

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

    // Build the parent location name.
    $locationName = $client->locationName($projectId, $locationId);

    // Build the key ring.
    $keyRing = new KeyRing();

    // Call the API.
    $createKeyRingRequest = (new CreateKeyRingRequest())
        ->setParent($locationName)
        ->setKeyRingId($id)
        ->setKeyRing($keyRing);
    $createdKeyRing = $client->createKeyRing($createKeyRingRequest);
    printf('Created key ring: %s' . PHP_EOL, $createdKeyRing->getName());

    return $createdKeyRing;
}

Python

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

from google.cloud import kms


def create_key_ring(
    project_id: str, location_id: str, key_ring_id: str
) -> kms.CryptoKey:
    """
    Creates a new key ring 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 key ring to create (e.g. 'my-key-ring').

    Returns:
        KeyRing: Cloud KMS key ring.

    """

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

    # Build the parent location name.
    location_name = f"projects/{project_id}/locations/{location_id}"

    # Build the key ring.
    key_ring = {}

    # Call the API.
    created_key_ring = client.create_key_ring(
        request={
            "parent": location_name,
            "key_ring_id": key_ring_id,
            "key_ring": key_ring,
        }
    )
    print(f"Created key ring: {created_key_ring.name}")
    return created_key_ring

Ruby

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

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# id = "my-key-ring"

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

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

# Build the parent location name.
location_name = client.location_path project: project_id, location: location_id

# Build the key ring.
key_ring = {}

# Call the API.
created_key_ring = client.create_key_ring parent: location_name, key_ring_id: id, key_ring: key_ring
puts "Created key ring: #{created_key_ring.name}"

API

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

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

다음을 바꿉니다.

  • PROJECT_ID: 키링이 포함된 프로젝트의 ID입니다.
  • KEY_RING: 키가 포함된 키링의 이름입니다.
  • LOCATION: 키링의 Cloud KMS 위치입니다.

자세한 내용은 KeyRing.create API 참고 리소스를 참조하세요.

키 만들기

지정된 키링 및 위치에 Cloud HSM 키를 만들려면 다음 단계를 따르세요.

콘솔

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

    키 관리 페이지로 이동

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

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

  4. 어떤 유형의 키를 만드시겠어요?에서 생성된 키를 선택합니다.

  5. 키 이름 필드에 키의 이름을 입력합니다.

  6. 보호 수준 드롭다운을 클릭하고 HSM 또는 단독 테넌트 HSM을 선택합니다.

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

  8. 용도 드롭다운을 클릭하고 대칭 암호화/복호화를 선택합니다.

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

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

gcloud

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

멀티 테넌트 Cloud HSM 키를 만들려면 hsm 보호 수준으로 kms keys create 명령어를 실행합니다.

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

다음을 바꿉니다.

  • KEY_NAME: 키에 사용할 이름입니다.
  • KEY_RING: 키를 만들 키링의 이름입니다.
  • LOCATION: 키링의 위치입니다.

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

단일 테넌트 Cloud HSM 키를 만들려면 hsm-single-tenant 보호 수준으로 kms keys create 명령어를 실행하고 키를 만들려는 단일 테넌트 Cloud HSM 인스턴스를 지정합니다. 단독 테넌트 Cloud HSM 인스턴스는 키링과 동일한 위치에 있어야 합니다.

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"

다음을 바꿉니다.

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

C#

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


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

public class CreateKeyHsmSample
{
    public CryptoKey CreateKeyHsm(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-hsm-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
            {
                ProtectionLevel = ProtectionLevel.Hsm,
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            },

            // Optional: customize how long key versions should be kept before destroying.
            DestroyScheduledDuration = new Duration
            {
                Seconds = 24 * 60 * 60,
            }
        };

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

// createKeyHSM creates a new symmetric encrypt/decrypt key on Cloud KMS.
func createKeyHSM(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-hsm-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{
				ProtectionLevel: kmspb.ProtectionLevel_HSM,
				Algorithm:       kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},

			// Optional: customize how long key versions should be kept before destroying.
			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
		},
	}

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