루트 인증 기관 만들기

이 페이지에서는 CA 풀에서 루트 인증 기관(CA)을 만드는 방법을 설명합니다.

루트 CA는 공개 키 인프라(PKI) 계층 구조의 맨 위에 있으며 PKI의 신뢰 앵커를 형성합니다. PKI에서 인증서를 올바르게 함께 사용하려면 기기, 소프트웨어 또는 구성요소가 PKI를 신뢰해야 합니다. 이렇게 하려면 루트 CA를 신뢰하도록 기기, 소프트웨어, 구성요소를 구성합니다. 그러면 루트 CA에서 발급된 모든 인증서를 신뢰할 수 있습니다.

시작하기 전에

루트 CA 만들기

루트 CA에는 자체 서명 인증서가 있으며, 이는 클라이언트의 트러스트 저장소에 배포해야 합니다. 루트 CA의 인증서는 인증서 체인의 맨 위에 있습니다. 다른 CA로 이 CA 인증서를 해지할 수 없습니다. 루트 CA의 CRL은 루트 CA가 발급한 다른 인증서에만 적용되며 그 자체로는 적용되지 않습니다.

콘솔

루트 CA를 만들려면 다음을 수행하세요.

  1. Google Cloud 콘솔에서 Certificate Authority Service 페이지로 이동합니다.

    Certificate Authority Service로 이동

  2. CA 관리자 탭을 클릭합니다.

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

CA 유형 선택

등급, 위치, 수명, 생성 시 작동 상태와 같은 CA의 영구적인 설정을 구성하려면 다음 안내를 따르세요.

  1. 루트 CA를 선택합니다.
  2. 유효 기간 필드에 CA 인증서에서 발급한 인증서가 유효해야 할 기간을 입력합니다.
  3. 선택사항: CA 등급을 선택합니다.
  4. 리전을 클릭하고 목록에서 CA를 만들려는 위치를 선택합니다. 애플리케이션의 클라이언트와 지리적으로 가까운 곳에 CA를 만드는 것이 좋습니다. 자세한 내용은 최적의 위치 선택을 참조하세요.
  5. 선택사항: 생성할 CA의 작동 상태를 선택합니다.

    생성될 CA의 작업 상태 선택

  6. 선택사항: 인증서 프로필을 클릭합니다. 목록에서 CA에서 발급할 인증서 유형과 일치하는 인증서 프로필을 선택합니다.

  7. 다음을 클릭합니다.

CA 주체 이름 구성
  1. 조직(O) 필드에 회사 이름을 입력합니다.
  2. 선택사항: 조직 단위(OU) 필드에 회사 부서 또는 사업부를 입력합니다.
  3. 선택사항: 국가 이름 필드에 2자리 국가 코드를 입력합니다.
  4. 선택사항: 주/도 이름 필드에 주 이름을 입력합니다.
  5. 선택사항: 지역 이름 필드에 도시 이름을 입력합니다.
  6. CA 일반 이름(CN) 필드에 CA 이름을 입력합니다.
  7. 풀 ID 필드에 CA 풀 이름을 입력합니다. CA를 만든 후에는 CA 풀을 변경할 수 없습니다.
  8. 다음을 클릭합니다.
CA 키 크기 및 알고리즘 구성
  1. 요구사항에 가장 부합하는 키 알고리즘을 선택합니다. 적절한 키 알고리즘 결정에 대한 자세한 내용은 키 알고리즘 선택을 참조하세요.
  2. 다음을 클릭합니다.
CA 아티팩트 구성

다음 단계는 선택사항입니다. 이 단계를 건너뛰면 기본 설정이 적용됩니다.

  1. Google 관리형 또는 자체 관리형 Cloud Storage 버킷 사용 여부를 선택합니다.
  2. 자체 관리형 Cloud Storage 버킷을 선택하지 않으면 CA Service는 CA와 동일한 위치에 Google 관리 버킷을 만듭니다.

  3. 해지 인증서 목록(CRL) 및 CA 인증서의 Cloud Storage 버킷 게시를 중지할지 여부를 선택합니다.
  4. CRL 및 CA 인증서의 Cloud Storage 버킷 게시는 기본적으로 사용 설정되어 있습니다. 이 설정을 중지하려면 전환 버튼을 클릭합니다.

  5. 다음을 클릭합니다.
라벨 추가

다음 단계는 선택사항입니다.

CA에 라벨을 추가하려면 다음을 수행합니다.

  1. 항목 추가를 클릭합니다.
  2. 키 1 필드에 라벨 키를 입력합니다.
  3. 값 1 필드에 라벨 값을 입력합니다.
  4. 다른 라벨을 추가하려면 항목 추가를 클릭합니다. 그런 다음 2단계와 3단계에 설명된 대로 라벨 키와 값을 추가합니다.
  5. 다음을 클릭합니다.
설정 검토

모든 설정을 신중하게 검토한 다음 만들기를 클릭하여 CA를 만듭니다.

gcloud

  1. CA 풀을 만들려면 다음 명령어를 실행합니다.

    gcloud privateca pools create POOL_ID
    

    POOL_ID를 CA 풀의 이름으로 바꿉니다.

    자세한 내용은 CA 풀 만들기를 참조하세요.

    gcloud 명령어에 대한 자세한 내용은 gcloud privateca pools create를 참조하세요.

  2. 자신이 만든 CA 풀에서 새 루트 CA를 만듭니다.

    gcloud privateca roots create ROOT_CA_ID --pool=POOL_ID \
      --key-algorithm=KEY_ALGORITHM \
      --subject="CN=my-ca, O=Test LLC"
    

    다음을 바꿉니다.

    • ROOT_CA_ID: CA의 이름입니다.
    • POOL_ID: CA 풀의 이름입니다.
    • KEY_ALGORITHM: Cloud KMS 키를 만드는 데 사용할 알고리즘입니다. 이 플래그는 선택사항입니다. 이 플래그를 포함하지 않으면 키 알고리즘이 기본적으로 rsa-pkcs1-4096-sha256으로 설정됩니다. 자세한 내용은 --key-algorithm 플래그를 참조하세요.

    기본적으로 CA는 STAGED 상태로 생성됩니다. CA를 기본적으로 사용 설정하려면 --auto-enable 플래그를 포함합니다.

    CA 인증서 및 CRL을 게시하는 데 고객 관리 Cloud Storage 버킷을 사용하려면 명령어에 --bucket bucket-name을 추가합니다. bucket-name을 Cloud Storage 버킷의 이름으로 바꿉니다.

    전체 설정 목록을 보려면 다음 명령어를 실행합니다.

    gcloud privateca roots create --help
    

Terraform

Google 관리 키를 사용하여 루트 CA를 만들려면 다음 샘플 구성을 사용합니다.

resource "google_privateca_certificate_authority" "default" {
  // This example assumes this pool already exists.
  // Pools cannot be deleted in normal test circumstances, so we depend on static pools
  pool                     = "my-pool"
  certificate_authority_id = "my-certificate-authority-hashicorp"
  location                 = "us-central1"
  deletion_protection      = false # set to true to prevent destruction of the resource
  config {
    subject_config {
      subject {
        organization = "HashiCorp"
        common_name  = "my-certificate-authority"
      }
      subject_alt_name {
        dns_names = ["hashicorp.com"]
      }
    }
    x509_config {
      ca_options {
        is_ca                  = true
        max_issuer_path_length = 10
      }
      key_usage {
        base_key_usage {
          digital_signature  = true
          content_commitment = true
          key_encipherment   = false
          data_encipherment  = true
          key_agreement      = true
          cert_sign          = true
          crl_sign           = true
          decipher_only      = true
        }
        extended_key_usage {
          server_auth      = true
          client_auth      = false
          email_protection = true
          code_signing     = true
          time_stamping    = true
        }
      }
    }
  }
  lifetime = "86400s"
  key_spec {
    algorithm = "RSA_PKCS1_4096_SHA256"
  }
}

자체 관리 키를 사용하여 루트 CA를 만들려면 다음 샘플 구성을 사용합니다.

resource "google_project_service_identity" "privateca_sa" {
  provider = google-beta
  service  = "privateca.googleapis.com"
}

resource "google_kms_crypto_key_iam_binding" "privateca_sa_keyuser_signerverifier" {
  crypto_key_id = "projects/keys-project/locations/us-central1/keyRings/key-ring/cryptoKeys/crypto-key"
  role          = "roles/cloudkms.signerVerifier"

  members = [
    "serviceAccount:${google_project_service_identity.privateca_sa.email}",
  ]
}

resource "google_kms_crypto_key_iam_binding" "privateca_sa_keyuser_viewer" {
  crypto_key_id = "projects/keys-project/locations/us-central1/keyRings/key-ring/cryptoKeys/crypto-key"
  role          = "roles/viewer"
  members = [
    "serviceAccount:${google_project_service_identity.privateca_sa.email}",
  ]
}

resource "google_privateca_certificate_authority" "default" {
  // This example assumes this pool already exists.
  // Pools cannot be deleted in normal test circumstances, so we depend on static pools
  pool                     = "ca-pool"
  certificate_authority_id = "my-certificate-authority"
  location                 = "us-central1"
  deletion_protection      = false # set to true to prevent destruction of the resource
  key_spec {
    cloud_kms_key_version = "projects/keys-project/locations/us-central1/keyRings/key-ring/cryptoKeys/crypto-key/cryptoKeyVersions/1"
  }

  config {
    subject_config {
      subject {
        organization = "Example, Org."
        common_name  = "Example Authority"
      }
    }
    x509_config {
      ca_options {
        # is_ca *MUST* be true for certificate authorities
        is_ca                  = true
        max_issuer_path_length = 10
      }
      key_usage {
        base_key_usage {
          # cert_sign and crl_sign *MUST* be true for certificate authorities
          cert_sign = true
          crl_sign  = true
        }
        extended_key_usage {
          server_auth = false
        }
      }
    }
  }

  depends_on = [
    google_kms_crypto_key_iam_binding.privateca_sa_keyuser_signerverifier,
    google_kms_crypto_key_iam_binding.privateca_sa_keyuser_viewer,
  ]
}

Go

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	privateca "cloud.google.com/go/security/privateca/apiv1"
	"cloud.google.com/go/security/privateca/apiv1/privatecapb"
	"google.golang.org/protobuf/types/known/durationpb"
)

// Create Certificate Authority which is the root CA in the given CA Pool. This CA will be
// responsible for signing certificates within this pool.
func createCa(
	w io.Writer,
	projectId string,
	location string,
	caPoolId string,
	caId string,
	caCommonName string,
	org string,
	caDuration int64) error {
	// projectId := "your_project_id"
	// location := "us-central1"		// For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
	// caPoolId := "ca-pool-id"			// The CA Pool id under which the CA should be created.
	// caId := "ca-id"					// A unique id/name for the ca.
	// caCommonName := "ca-name"		// A common name for your certificate authority.
	// org := "ca-org"					// The name of your company for your certificate authority.
	// ca_duration := int64(31536000)	// The validity of the certificate authority in seconds.

	ctx := context.Background()
	caClient, err := privateca.NewCertificateAuthorityClient(ctx)
	if err != nil {
		return fmt.Errorf("NewCertificateAuthorityClient creation failed: %w", err)
	}
	defer caClient.Close()

	// Set the types of Algorithm used to create a cloud KMS key.
	keySpec := &privatecapb.CertificateAuthority_KeyVersionSpec{
		KeyVersion: &privatecapb.CertificateAuthority_KeyVersionSpec_Algorithm{
			Algorithm: privatecapb.CertificateAuthority_RSA_PKCS1_2048_SHA256,
		},
	}

	// Set CA subject config.
	subjectConfig := &privatecapb.CertificateConfig_SubjectConfig{
		Subject: &privatecapb.Subject{
			CommonName:   caCommonName,
			Organization: org,
		},
	}

	// Set the key usage options for X.509 fields.
	isCa := true
	x509Parameters := &privatecapb.X509Parameters{
		KeyUsage: &privatecapb.KeyUsage{
			BaseKeyUsage: &privatecapb.KeyUsage_KeyUsageOptions{
				CrlSign:  true,
				CertSign: true,
			},
		},
		CaOptions: &privatecapb.X509Parameters_CaOptions{
			IsCa: &isCa,
		},
	}

	// Set certificate authority settings.
	// Type: SELF_SIGNED denotes that this CA is a root CA.
	ca := &privatecapb.CertificateAuthority{
		Type:    privatecapb.CertificateAuthority_SELF_SIGNED,
		KeySpec: keySpec,
		Config: &privatecapb.CertificateConfig{
			SubjectConfig: subjectConfig,
			X509Config:    x509Parameters,
		},
		Lifetime: &durationpb.Duration{
			Seconds: caDuration,
		},
	}

	fullCaPoolName := fmt.Sprintf("projects/%s/locations/%s/caPools/%s", projectId, location, caPoolId)

	// Create the CreateCertificateAuthorityRequest.
	// See https://pkg.go.dev/cloud.google.com/go/security/privateca/apiv1/privatecapb#CreateCertificateAuthorityRequest.
	req := &privatecapb.CreateCertificateAuthorityRequest{
		Parent:                 fullCaPoolName,
		CertificateAuthorityId: caId,
		CertificateAuthority:   ca,
	}

	op, err := caClient.CreateCertificateAuthority(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateCertificateAuthority failed: %w", err)
	}

	if _, err = op.Wait(ctx); err != nil {
		return fmt.Errorf("CreateCertificateAuthority failed during wait: %w", err)
	}

	fmt.Fprintf(w, "CA %s created", caId)

	return nil
}

Java

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.api.core.ApiFuture;
import com.google.cloud.security.privateca.v1.CaPoolName;
import com.google.cloud.security.privateca.v1.CertificateAuthority;
import com.google.cloud.security.privateca.v1.CertificateAuthority.KeyVersionSpec;
import com.google.cloud.security.privateca.v1.CertificateAuthority.SignHashAlgorithm;
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
import com.google.cloud.security.privateca.v1.CertificateConfig;
import com.google.cloud.security.privateca.v1.CertificateConfig.SubjectConfig;
import com.google.cloud.security.privateca.v1.CreateCertificateAuthorityRequest;
import com.google.cloud.security.privateca.v1.KeyUsage;
import com.google.cloud.security.privateca.v1.KeyUsage.KeyUsageOptions;
import com.google.cloud.security.privateca.v1.Subject;
import com.google.cloud.security.privateca.v1.X509Parameters;
import com.google.cloud.security.privateca.v1.X509Parameters.CaOptions;
import com.google.longrunning.Operation;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class CreateCertificateAuthority {

  public static void main(String[] args)
      throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    // location: For a list of locations, see:
    // https://cloud.google.com/certificate-authority-service/docs/locations
    // poolId: Set it to the CA Pool under which the CA should be created.
    // certificateAuthorityName: Unique name for the CA.
    String project = "your-project-id";
    String location = "ca-location";
    String poolId = "ca-pool-id";
    String certificateAuthorityName = "certificate-authority-name";
    createCertificateAuthority(project, location, poolId, certificateAuthorityName);
  }

  // Create Certificate Authority which is the root CA in the given CA Pool.
  public static void createCertificateAuthority(
      String project, String location, String poolId, String certificateAuthorityName)
      throws InterruptedException, ExecutionException, 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 `certificateAuthorityServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (CertificateAuthorityServiceClient certificateAuthorityServiceClient =
        CertificateAuthorityServiceClient.create()) {

      String commonName = "common-name";
      String orgName = "org-name";
      int caDuration = 100000; // Validity of this CA in seconds.

      // Set the type of Algorithm.
      KeyVersionSpec keyVersionSpec =
          KeyVersionSpec.newBuilder().setAlgorithm(SignHashAlgorithm.RSA_PKCS1_4096_SHA256).build();

      // Set CA subject config.
      SubjectConfig subjectConfig =
          SubjectConfig.newBuilder()
              .setSubject(
                  Subject.newBuilder().setCommonName(commonName).setOrganization(orgName).build())
              .build();

      //  Set the key usage options for X.509 fields.
      X509Parameters x509Parameters =
          X509Parameters.newBuilder()
              .setKeyUsage(
                  KeyUsage.newBuilder()
                      .setBaseKeyUsage(
                          KeyUsageOptions.newBuilder().setCrlSign(true).setCertSign(true).build())
                      .build())
              .setCaOptions(CaOptions.newBuilder().setIsCa(true).build())
              .build();

      // Set certificate authority settings.
      CertificateAuthority certificateAuthority =
          CertificateAuthority.newBuilder()
              // CertificateAuthority.Type.SELF_SIGNED denotes that this CA is a root CA.
              .setType(CertificateAuthority.Type.SELF_SIGNED)
              .setKeySpec(keyVersionSpec)
              .setConfig(
                  CertificateConfig.newBuilder()
                      .setSubjectConfig(subjectConfig)
                      .setX509Config(x509Parameters)
                      .build())
              // Set the CA validity duration.
              .setLifetime(Duration.newBuilder().setSeconds(caDuration).build())
              .build();

      // Create the CertificateAuthorityRequest.
      CreateCertificateAuthorityRequest certificateAuthorityRequest =
          CreateCertificateAuthorityRequest.newBuilder()
              .setParent(CaPoolName.of(project, location, poolId).toString())
              .setCertificateAuthorityId(certificateAuthorityName)
              .setCertificateAuthority(certificateAuthority)
              .build();

      // Create Certificate Authority.
      ApiFuture<Operation> futureCall =
          certificateAuthorityServiceClient
              .createCertificateAuthorityCallable()
              .futureCall(certificateAuthorityRequest);
      Operation response = futureCall.get();

      if (response.hasError()) {
        System.out.println("Error while creating CA !" + response.getError());
        return;
      }

      System.out.println(
          "Certificate Authority created successfully : " + certificateAuthorityName);
    }
  }
}

Python

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import google.cloud.security.privateca_v1 as privateca_v1
from google.protobuf import duration_pb2

def create_certificate_authority(
    project_id: str,
    location: str,
    ca_pool_name: str,
    ca_name: str,
    common_name: str,
    organization: str,
    ca_duration: int,
) -> None:
    """
    Create Certificate Authority which is the root CA in the given CA Pool. This CA will be
    responsible for signing certificates within this pool.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
        ca_pool_name: set it to the CA Pool under which the CA should be created.
        ca_name: unique name for the CA.
        common_name: a title for your certificate authority.
        organization: the name of your company for your certificate authority.
        ca_duration: the validity of the certificate authority in seconds.
    """

    caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

    # Set the types of Algorithm used to create a cloud KMS key.
    key_version_spec = privateca_v1.CertificateAuthority.KeyVersionSpec(
        algorithm=privateca_v1.CertificateAuthority.SignHashAlgorithm.RSA_PKCS1_4096_SHA256
    )

    # Set CA subject config.
    subject_config = privateca_v1.CertificateConfig.SubjectConfig(
        subject=privateca_v1.Subject(common_name=common_name, organization=organization)
    )

    # Set the key usage options for X.509 fields.
    x509_parameters = privateca_v1.X509Parameters(
        key_usage=privateca_v1.KeyUsage(
            base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions(
                crl_sign=True,
                cert_sign=True,
            )
        ),
        ca_options=privateca_v1.X509Parameters.CaOptions(
            is_ca=True,
        ),
    )

    # Set certificate authority settings.
    certificate_authority = privateca_v1.CertificateAuthority(
        # CertificateAuthority.Type.SELF_SIGNED denotes that this CA is a root CA.
        type_=privateca_v1.CertificateAuthority.Type.SELF_SIGNED,
        key_spec=key_version_spec,
        config=privateca_v1.CertificateConfig(
            subject_config=subject_config,
            x509_config=x509_parameters,
        ),
        lifetime=duration_pb2.Duration(seconds=ca_duration),
    )

    ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name)

    # Create the CertificateAuthorityRequest.
    request = privateca_v1.CreateCertificateAuthorityRequest(
        parent=ca_pool_path,
        certificate_authority_id=ca_name,
        certificate_authority=certificate_authority,
    )

    operation = caServiceClient.create_certificate_authority(request=request)
    result = operation.result()

    print("Operation result:", result)

REST API

  1. 루트 CA를 만듭니다.

    HTTP 메서드 및 URL:

    POST https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/caPools/POOL_ID/certificateAuthorities?certificate_authority_id=ROOT_CA_ID

    JSON 요청 본문:

    {
    "type": "SELF_SIGNED",
    "lifetime": {
     "seconds": 315576000,
     "nanos": 0
    },
    "config": {
     "subject_config": {
       "subject": {
         "organization": "ORGANIZATION_NAME",
         "common_name": "COMMON_NAME"
       }
     },
     "x509_config":{
       "ca_options":{
         "is_ca":true
       },
       "key_usage":{
         "base_key_usage":{
           "cert_sign":true,
           "crl_sign":true
         }
       }
     }
    },
    "key_spec":{
     "algorithm":"RSA_PKCS1_4096_SHA256"
    }
    }
    

    요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

    다음과 비슷한 JSON 응답이 표시됩니다.

    {
     "name": "projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID",
     "metadata": {...},
     "done": false
    }
    

  2. 작업이 완료될 때까지 작업을 폴링합니다.

    HTTP 메서드 및 URL:

    GET https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID

    요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

    다음과 비슷한 JSON 응답이 표시됩니다.

    {
     "name": "projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID",
     "metadata": {...},
     "done": true,
     "response": {
       "@type": "type.googleapis.com/google.cloud.security.privateca.v1.CertificateAuthority",
       "name": "...",
     }
    }
    

CA가 예상대로 작동하는지 확인되면 CA 풀을 위한 부하 분산 인증서의 발급을 시작하도록 사용 설정할 수 있습니다.

루트 CA 사용 설정

gcloud

루트 CA를 사용 설정하려면 다음 gcloud 명령어를 실행합니다.

gcloud privateca roots enable ROOT_CA_ID --pool=POOL_ID

다음을 바꿉니다.

  • ROOT_CA_ID: CA의 이름입니다.
  • POOL_ID: CA 풀의 이름입니다.

Terraform

Terraform을 사용하여 루트 CA를 만드는 경우, 루트 CA가 생성 시 사용 설정됩니다. STAGED 상태의 루트 CA를 만들려면 CA를 만들 때 desired_state 필드를 STAGED로 설정합니다.

CA 생성 후 desired_state 필드를 ENABLED 또는 DISABLED로 설정할 수 있습니다.

Go

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	privateca "cloud.google.com/go/security/privateca/apiv1"
	"cloud.google.com/go/security/privateca/apiv1/privatecapb"
)

// Enable the Certificate Authority present in the given ca pool.
// CA cannot be enabled if it has been already deleted.
func enableCa(w io.Writer, projectId string, location string, caPoolId string, caId string) error {
	// projectId := "your_project_id"
	// location := "us-central1"	// For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
	// caPoolId := "ca-pool-id"		// The id of the CA pool under which the CA is present.
	// caId := "ca-id"				// The id of the CA to be enabled.

	ctx := context.Background()
	caClient, err := privateca.NewCertificateAuthorityClient(ctx)
	if err != nil {
		return fmt.Errorf("NewCertificateAuthorityClient creation failed: %w", err)
	}
	defer caClient.Close()

	fullCaName := fmt.Sprintf("projects/%s/locations/%s/caPools/%s/certificateAuthorities/%s",
		projectId, location, caPoolId, caId)

	// Create the EnableCertificateAuthorityRequest.
	// See https://pkg.go.dev/cloud.google.com/go/security/privateca/apiv1/privatecapb#EnableCertificateAuthorityRequest.
	req := &privatecapb.EnableCertificateAuthorityRequest{Name: fullCaName}

	op, err := caClient.EnableCertificateAuthority(ctx, req)
	if err != nil {
		return fmt.Errorf("EnableCertificateAuthority failed: %w", err)
	}

	var caResp *privatecapb.CertificateAuthority
	if caResp, err = op.Wait(ctx); err != nil {
		return fmt.Errorf("EnableCertificateAuthority failed during wait: %w", err)
	}

	if caResp.State != privatecapb.CertificateAuthority_ENABLED {
		return fmt.Errorf("unable to enable Certificate Authority. Current state: %s", caResp.State.String())
	}

	fmt.Fprintf(w, "Successfully enabled Certificate Authority: %s.", caId)
	return nil
}

Java

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.api.core.ApiFuture;
import com.google.cloud.security.privateca.v1.CertificateAuthority.State;
import com.google.cloud.security.privateca.v1.CertificateAuthorityName;
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
import com.google.cloud.security.privateca.v1.EnableCertificateAuthorityRequest;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class EnableCertificateAuthority {

  public static void main(String[] args)
      throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    // location: For a list of locations, see:
    // https://cloud.google.com/certificate-authority-service/docs/locations
    // poolId: The id of the CA pool under which the CA is present.
    // certificateAuthorityName: The name of the CA to be enabled.
    String project = "your-project-id";
    String location = "ca-location";
    String poolId = "ca-pool-id";
    String certificateAuthorityName = "certificate-authority-name";
    enableCertificateAuthority(project, location, poolId, certificateAuthorityName);
  }

  // Enable the Certificate Authority present in the given ca pool.
  // CA cannot be enabled if it has been already deleted.
  public static void enableCertificateAuthority(
      String project, String location, String poolId, String certificateAuthorityName)
      throws IOException, ExecutionException, InterruptedException {
    try (CertificateAuthorityServiceClient certificateAuthorityServiceClient =
        CertificateAuthorityServiceClient.create()) {
      // Create the Certificate Authority Name.
      CertificateAuthorityName certificateAuthorityParent =
          CertificateAuthorityName.newBuilder()
              .setProject(project)
              .setLocation(location)
              .setCaPool(poolId)
              .setCertificateAuthority(certificateAuthorityName)
              .build();

      // Create the Enable Certificate Authority Request.
      EnableCertificateAuthorityRequest enableCertificateAuthorityRequest =
          EnableCertificateAuthorityRequest.newBuilder()
              .setName(certificateAuthorityParent.toString())
              .build();

      // Enable the Certificate Authority.
      ApiFuture<Operation> futureCall =
          certificateAuthorityServiceClient
              .enableCertificateAuthorityCallable()
              .futureCall(enableCertificateAuthorityRequest);
      Operation response = futureCall.get();

      if (response.hasError()) {
        System.out.println("Error while enabling Certificate Authority !" + response.getError());
        return;
      }

      // Get the current CA state.
      State caState =
          certificateAuthorityServiceClient
              .getCertificateAuthority(certificateAuthorityParent)
              .getState();

      // Check if the CA is enabled.
      if (caState == State.ENABLED) {
        System.out.println("Enabled Certificate Authority : " + certificateAuthorityName);
      } else {
        System.out.println(
            "Cannot enable the Certificate Authority ! Current CA State: " + caState);
      }
    }
  }
}

Python

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import google.cloud.security.privateca_v1 as privateca_v1

def enable_certificate_authority(
    project_id: str, location: str, ca_pool_name: str, ca_name: str
) -> None:
    """
    Enable the Certificate Authority present in the given ca pool.
    CA cannot be enabled if it has been already deleted.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
        ca_pool_name: the name of the CA pool under which the CA is present.
        ca_name: the name of the CA to be enabled.
    """

    caServiceClient = privateca_v1.CertificateAuthorityServiceClient()
    ca_path = caServiceClient.certificate_authority_path(
        project_id, location, ca_pool_name, ca_name
    )

    # Create the Enable Certificate Authority Request.
    request = privateca_v1.EnableCertificateAuthorityRequest(
        name=ca_path,
    )

    # Enable the Certificate Authority.
    operation = caServiceClient.enable_certificate_authority(request=request)
    operation.result()

    # Get the current CA state.
    ca_state = caServiceClient.get_certificate_authority(name=ca_path).state

    # Check if the CA is enabled.
    if ca_state == privateca_v1.CertificateAuthority.State.ENABLED:
        print("Enabled Certificate Authority:", ca_name)
    else:
        print("Cannot enable the Certificate Authority ! Current CA State:", ca_state)

REST API

  1. CA 풀에서 인증서를 발급하도록 CA를 사용 설정합니다.

    HTTP 메서드 및 URL:

    POST https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/caPools/POOL_ID/certificateAuthorities/ROOT_CA_ID:enable

    요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

    다음과 비슷한 JSON 응답이 표시됩니다.

    {
     "name": "projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID",
     "metadata": {...},
     "done": false
    }
    

  2. 작업이 완료될 때까지 작업을 폴링합니다.

    HTTP 메서드 및 URL:

    GET https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID

    요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

    다음과 비슷한 JSON 응답이 표시됩니다.

    {
     "name": "projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID",
     "metadata": {...},
     "done": true,
     "response": {
       "@type": "type.googleapis.com/google.cloud.security.privateca.v1.CertificateAuthority",
       "name": "...",
     }
    }
    

CA 테스트

CA가 인증서를 발급할 수 있는지 확인하려면 연결된 CA 풀에서 인증서를 요청하고 --ca 플래그를 사용하여 테스트할 CA 이름을 명시적으로 언급합니다.

다음 방법을 사용하여 CA 풀에서 인증서를 요청할 수 있습니다.

  1. CA Service에서 자동으로 비공개 또는 공개 키를 만들도록 합니다.
  2. 자체 비공개/공개 키를 생성하고 인증서 서명 요청(CSR)을 제출합니다.

자동 생성된 비공개 키나 공개 키를 사용하면 더 쉽게 CA 풀의 CA에서 인증서를 요청할 수 있습니다. 이 섹션에서는 이 방법을 사용하여 CA를 테스트하는 방법을 설명합니다.

자동 생성된 비공개 키 또는 공개 키를 사용하여 CA 풀의 CA에서 인증서를 요청하려면 다음 gcloud 명령어를 실행합니다.

gcloud privateca certificates create \
  --issuer-pool=POOL_ID \
  --ca=ROOT_CA_ID \
  --generate-key \
  --key-output-file=KEY_FILENAME \
  --cert-output-file=CERT_FILENAME \
  --dns-san=DNS_NAME

다음을 바꿉니다.

  • POOL_ID: CA 풀의 이름입니다.
  • ROOT_CA_ID: 테스트하려는 CA의 고유 식별자입니다.
  • KEY_FILENAME: 생성된 키가 PEM 형식으로 작성되는 파일입니다.
  • CERT_FILENAME: 결과로 생성된 PEM 인코딩 인증서 체인 파일이 작성되는 파일입니다. 인증서 체인의 순서는 리프에서 루트순으로 정렬됩니다.
  • DNS_NAME: 쉼표로 구분된 하나 이상의 DNS 주체 대체 이름(SAN)입니다.

    --generate-key 플래그는 머신에 새 RSA-2048 비공개 키를 생성합니다.

인증서 서명 요청(CSR)을 사용하여 CA 풀의 CA에서 인증서를 요청하거나 인증서 요청에 대해 자세히 알아보려면 인증서 요청 및 발급된 인증서 보기를 참조하세요.

인증 기관 클론

기존 CA를 클론하여 해당 CA를 갱신하거나 동일한 구성으로 새 CA를 만들려면 다음 명령어를 실행합니다.

gcloud privateca roots create NEW_CA_ID --pool=POOL_ID \
  --from-ca=EXISTING_CA_ID \
  --key-algorithm "ec-p384-sha384"

다음을 바꿉니다.

  • NEW_CA_ID: 새 CA의 고유 식별자입니다.
  • POOL_ID: 새 CA를 만들 CA 풀의 이름입니다.

--from-ca 플래그는 루트 및 하위 CA 만들기에 지원됩니다. 기존 CA는 새 CA와 동일한 CA 풀에 있어야 합니다.

--key-algorithm 플래그는 기존 CA에서 (Cloud KMS 키 버전 및 Cloud Storage 버킷을 제외한) 모든 CA 구성을 복사합니다. 그러나 적절한 플래그를 명시적으로 제공하여 새 CA에서 구성 값을 재정의할 수 있습니다. 예를 들어 새 주체를 사용하도록 `--subject SUBJECT를 지정할 수 있습니다.

--key-algorithm 플래그를 생략하면 알고리즘이 기본적으로 다음과 같이 지정됩니다.

  • 루트 CA의 경우 rsa-pkcs1-4096-sha256
  • 하위 CA의 경우 rsa-pkcs1-2048-sha256

gcloud 명령어에 대한 자세한 내용은 gcloud privateca roots create를 참조하세요.

다음 단계