인증서 요청 및 발급된 인증서 보기

이 주제에서는 Certificate Authority Service에서 인증서를 요청하고 발급된 인증서를 보는 방법을 설명합니다.

시작하기 전에

CA Service 인증서 요청자(roles/privateca.certificateRequester) 또는 CA Service 인증서 관리자(roles/privateca.certificateManager) IAM 역할이 있는지 확인합니다. CA Service의 사전 정의된 IAM 역할에 대한 자세한 내용은 IAM으로 액세스 제어를 참조하세요.

주 구성원에게 IAM 역할을 부여하는 방법에 대한 자세한 내용은 단일 역할 부여를 참조하세요.

개요

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

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

CSR을 사용하여 인증서 요청

계속하기 전에 CSR을 생성해야 합니다. CSR을 생성한 후 다음을 수행합니다.

콘솔

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

    Certificate Authority Service로 이동

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

  3. 발급할 CA의 이름을 클릭합니다.

  4. CA 세부정보 페이지 하단에서 인증서 요청을 클릭합니다.

  5. 선택사항: 인증서 템플릿을 사용하려면 를 클릭하고 목록에서 템플릿을 선택한 후 저장을 클릭합니다.

  6. CSR 제공을 클릭합니다.

  7. 선택사항: 자동으로 생성된 인증서 이름을 덮어쓰려면 인증서 이름 필드에 커스텀 이름을 입력합니다.

  8. 선택사항: 인증서의 커스텀 유효 기간을 선택하려면 유효 기간 필드에 값을 입력합니다.

  9. CSR을 복사하여 인증서 CSR 상자에 붙여넣습니다. CSR을 업로드하려면 찾아보기를 클릭합니다.

  10. 다음을 클릭합니다.

서명된 인증서 다운로드

  1. 인증서를 복사하려면 을 클릭합니다. .crt 파일 형식으로 인증서를 다운로드하려면 인증서 다운로드를 클릭합니다.
  2. 선택사항: 인증서 체인을 다운로드하려면 인증서 체인 다운로드를 클릭합니다.
  3. 완료를 클릭합니다.

gcloud

gcloud privateca certificates create CERT_ID \
     --issuer-pool POOL_ID \
     --csr CSR_FILENAME \
     --cert-output-file CERT_FILENAME \
     --validity "P30D"

다음을 바꿉니다.

  • CERT_ID: 인증서의 고유 식별자입니다.
  • POOL_ID: CA 풀의 이름입니다.
  • CSR_FILENAME: PEM으로 인코딩된 CSR을 저장하는 파일입니다.

--validity 플래그는 인증서가 유효한 기간을 정의합니다. 선택사항인 플래그로, 기본값이 30일입니다.

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

Terraform

resource "google_privateca_certificate_authority" "test_ca" {
  pool                     = "my-pool"
  certificate_authority_id = "my-certificate-authority"
  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 *MUST* be true for certificate authorities
        is_ca = true
      }
      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
        }
      }
    }
  }
  key_spec {
    algorithm = "RSA_PKCS1_4096_SHA256"
  }
}

resource "google_privateca_certificate" "default" {
  pool                  = "my-pool"
  location              = "us-central1"
  certificate_authority = google_privateca_certificate_authority.test_ca.certificate_authority_id
  lifetime              = "860s"
  name                  = "my-certificate"
  pem_csr               = tls_cert_request.example.cert_request_pem
}

resource "tls_private_key" "example" {
  algorithm = "RSA"
}

resource "tls_cert_request" "example" {
  private_key_pem = tls_private_key.example.private_key_pem

  subject {
    common_name  = "example.com"
    organization = "ACME Examples, Inc"
  }
}

REST API

  1. openssl 같은 원하는 방법을 사용하여 인증서 서명 요청(CSR)을 생성합니다.

    다음은 JSON으로 인코딩된 샘플 CSR입니다.

    -----BEGIN CERTIFICATE REQUEST-----\nMIIChTCCAW0CAQAwQDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQ8wDQYDVQQK\nDAZKb29uaXgxEzARBgNVBAMMCmpvb25peC5uZXQwggEiMA0GCSqGSIb3DQEBAQUA\nA4IBDwAwggEKAoIBAQCnyy+5vcRQUBPqAse3ojmWjyUvhcJK6eLRXpp0teEUF5kg\nHb2ov8gYXb9sSim5fnvs09dGYDKibSrL4Siy7lA/NzMzWtKwyQQeLIQq/cLUJVcd\ndItJ0VRcqr+UPkTCii2vrdcocNDChHM1J8chDdl6DkpYieSTqZwlPcWlQBGAINmT\nT3Q0ZarIVM5l74j13WPuToGrhbVOIZXWxWqJjlHbBA8B/VKtSRCzM1qG60y8Pu2f\n6c78Dfg8+CGRzGwnz8aFS0Yf9czT9luNHSadS/RHjvE9FPZCsinz+6mJlXRcphi1\nKaHsDbstUAhse1h5E9Biyr9SFYRHxY7qRv9aSJ/dAgMBAAGgADANBgkqhkiG9w0B\nAQsFAAOCAQEAZz+I9ff1Rf3lTewXRUpA7nr5HVO1ojCR93Pf27tI/hvNH7z7GwnS\noScoJlClxeRqABOCnfmVoRChullb/KmER4BZ/lF0GQpEtbqbjgjkEDpVlBKCb0+L\nHE9psplIz6H9nfFS3Ouoiodk902vrMEh0LyDYNQuqFoyCZuuepUlK3NmtmkexlgT\n0pJg/5FV0iaQ+GiFXSZhTC3drfiM/wDnXGiqpbW9WmebSij5O+3BNYXKBUgqmT3r\nbryFydNq4qSOIbnN/MNb4UoKno3ve7mnGk9lIDf9UMPvhl+bT7C3OLQLGadJroME\npYnKLoZUvRwEdtZpbNL9QhCAm2QiJ6w+6g==\n-----END CERTIFICATE REQUEST-----
    
  2. 인증서를 요청합니다.

    HTTP 메서드 및 URL:

    POST https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/caPools/POOL_ID/certificates?certificate_id=CERTIFICATE_ID

    JSON 요청 본문:

    {
     "lifetime": {
       "seconds": 3600,
       "nanos": 0
     },
     "pem_csr": "PEM_CSR"
    }
    

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

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

    {
     "name": "projects/project-id/locations/location/certificateAuthorities/ca-id/certificates/certificate-id",
     "pemCertificate": "-----BEGIN CERTIFICATE-----...",
     "certificateDescription": {...}
    }
    

자동 생성 키를 사용하여 인증서 요청

콘솔

Google Cloud 콘솔을 사용하여 클라이언트 또는 서버 TLS 인증서를 생성할 수 있습니다.

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

    Certificate Authority Service로 이동

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

  3. 발급할 CA의 이름을 클릭합니다.

  4. 인증 기관 세부정보 페이지 하단에서 인증서 요청을 클릭합니다.

  5. 선택사항: 인증서 템플릿을 사용하려면 를 클릭하고 목록에서 템플릿을 선택한 후 저장을 클릭합니다.

  6. 세부정보 입력을 클릭합니다.

  7. 선택사항: 자동 생성된 인증서 이름을 고유한 커스텀 이름으로 바꿉니다.

  8. 선택사항: 인증서의 커스텀 유효 기간을 선택하려면 유효 기간 필드에 값을 입력합니다.

도메인 이름 추가

  1. 도메인 이름 추가에서 도메인 이름 1 필드에 도메인 이름을 입력합니다.
  2. 선택사항: 도메인 이름을 두 개 이상 추가하려면 항목 추가를 클릭하고 도메인 이름 2 필드에 다른 도메인 이름을 입력합니다.

확장된 키 사용

  1. 선택사항: 확장된 키 사용에서 사용 사례에 따라 다음 옵션 중 하나를 선택합니다.

    • 서버 TLS: 이러한 인증서를 사용하면 서버의 ID를 인증할 수 있습니다.
    • 클라이언트 TLS: 이 인증서를 사용하면 요청자의 ID를 인증할 수 있습니다.
  2. 다음을 클릭합니다.

키 크기 및 알고리즘 구성

  1. 선택사항: 키 크기 및 알고리즘 구성의 목록에서 서명 키 크기 및 알고리즘을 선택합니다. 이 단계를 건너뛰면 SHA 256 다이제스트가 있는 RSASSA-PSS 2048비트 키가 사용됩니다. 서명 키 및 알고리즘 선택에 대한 자세한 내용은 키 알고리즘 선택을 참조하세요.
  2. 계속을 클릭합니다.

서명된 인증서 다운로드

  1. 선택사항: PEM으로 인코딩된 인증서 체인을 다운로드하려면 인증서 체인 다운로드를 클릭합니다.
  2. 선택사항: 연결된 PEM으로 인코딩된 비공개 키를 다운로드하려면 비공개 키 다운로드를 클릭합니다.

  3. 완료를 클릭합니다.

gcloud

자동 생성 키 기능을 사용하려면 Python 암호화 기관(PyCA) 라이브러리를 설치해야 합니다. Pyca 암호 라이브러리 설치에 대한 안내는 Pyca 암호화 라이브러리 포함을 참조하세요.

인증서를 만들려면 다음 gcloud 명령어를 사용합니다.

gcloud privateca certificates create \
  --issuer-pool POOL_ID \
  --generate-key \
  --key-output-file KEY_FILENAME \
  --cert-output-file CERT_FILENAME \
  --dns-san "DNS_NAME" \
  --use-preset-profile "CERTIFICATE_PROFILE"

다음을 바꿉니다.

  • POOL_ID: CA 풀의 이름입니다.
  • KEY_FILENAME: 생성된 비공개 키 파일을 작성해야 하는 경로입니다.
  • CERT_FILENAME: PEM으로 인코딩된 인증서 체인 파일을 작성해야 하는 경로입니다. 인증서 체인은 최종 항목에서 루트로 정렬됩니다.
  • DNS_NAME: 쉼표로 구분된 하나 이상의 DNS 주체 대체 이름(SAN)입니다.
  • CERTIFICATE_PROFILE: 인증서 프로필의 고유 식별자입니다. 예를 들어 최종 항목 서버 TLS의 경우 leaf_server_tls를 사용합니다.

gcloud 명령어에는 다음 플래그가 포함됩니다.

  • --generate-key: 머신에 새 RSA-2048 비공개 키를 생성합니다.

다음 플래그의 조합을 사용할 수도 있습니다.

  • --dns-san: 쉼표로 구분된 하나 이상의 DNS SAN을 전달할 수 있습니다.
  • --ip-san: 쉼표로 구분된 IP SAN을 하나 이상 전달할 수 있습니다.
  • --uri-san: 하나 이상의 쉼표로 구분된 URI SAN을 전달할 수 있습니다.
  • --subject: 인증서 주체의 X.501 이름을 전달할 수 있습니다.

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

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 a Certificate which is issued by the Certificate Authority present in the CA Pool.
// The key used to sign the certificate is created by the Cloud KMS.
func createCertificate(
	w io.Writer,
	projectId string,
	location string,
	caPoolId string,
	caId string,
	certId string,
	commonName string,
	domainName string,
	certDuration int64,
	publicKeyBytes []byte) 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 in which the certificate authority exists.
	// caId := "ca-id"					// The name of the certificate authority which issues the certificate.
	// certId := "certificate"			// A unique name for the certificate.
	// commonName := "cert-name"		// A common name for the certificate.
	// domainName := "cert.example.com"	// Fully qualified domain name for the certificate.
	// certDuration := int64(31536000)	// The validity of the certificate in seconds.
	// publicKeyBytes 					// The public key used in signing the certificates.

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

	// Set the Public Key and its format.
	publicKey := &privatecapb.PublicKey{
		Key:    publicKeyBytes,
		Format: privatecapb.PublicKey_PEM,
	}

	// Set Certificate subject config.
	subjectConfig := &privatecapb.CertificateConfig_SubjectConfig{
		Subject: &privatecapb.Subject{
			CommonName: commonName,
		},
		SubjectAltName: &privatecapb.SubjectAltNames{
			DnsNames: []string{domainName},
		},
	}

	// Set the X.509 fields required for the certificate.
	x509Parameters := &privatecapb.X509Parameters{
		KeyUsage: &privatecapb.KeyUsage{
			BaseKeyUsage: &privatecapb.KeyUsage_KeyUsageOptions{
				DigitalSignature: true,
				KeyEncipherment:  true,
			},
			ExtendedKeyUsage: &privatecapb.KeyUsage_ExtendedKeyUsageOptions{
				ServerAuth: true,
				ClientAuth: true,
			},
		},
	}

	// Set certificate settings.
	cert := &privatecapb.Certificate{
		CertificateConfig: &privatecapb.Certificate_Config{
			Config: &privatecapb.CertificateConfig{
				PublicKey:     publicKey,
				SubjectConfig: subjectConfig,
				X509Config:    x509Parameters,
			},
		},
		Lifetime: &durationpb.Duration{
			Seconds: certDuration,
		},
	}

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

	// Create the CreateCertificateRequest.
	// See https://pkg.go.dev/cloud.google.com/go/security/privateca/apiv1/privatecapb#CreateCertificateRequest.
	req := &privatecapb.CreateCertificateRequest{
		Parent:                        fullCaPoolName,
		CertificateId:                 certId,
		Certificate:                   cert,
		IssuingCertificateAuthorityId: caId,
	}

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

	fmt.Fprintf(w, "Certificate %s created", certId)

	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.Certificate;
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.CreateCertificateRequest;
import com.google.cloud.security.privateca.v1.KeyUsage;
import com.google.cloud.security.privateca.v1.KeyUsage.ExtendedKeyUsageOptions;
import com.google.cloud.security.privateca.v1.KeyUsage.KeyUsageOptions;
import com.google.cloud.security.privateca.v1.PublicKey;
import com.google.cloud.security.privateca.v1.PublicKey.KeyFormat;
import com.google.cloud.security.privateca.v1.Subject;
import com.google.cloud.security.privateca.v1.SubjectAltNames;
import com.google.cloud.security.privateca.v1.X509Parameters;
import com.google.cloud.security.privateca.v1.X509Parameters.CaOptions;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class CreateCertificate {

  public static void main(String[] args)
      throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.

    // publicKeyBytes: Public key used in signing the certificates.
    // location: For a list of locations, see:
    // https://cloud.google.com/certificate-authority-service/docs/locations
    // poolId: Set a unique id for the CA pool.
    // certificateAuthorityName: The name of the certificate authority which issues the certificate.
    // certificateName: Set a unique name for the certificate.
    String project = "your-project-id";
    ByteString publicKeyBytes = ByteString.copyFrom(new byte[]{});
    String location = "ca-location";
    String poolId = "ca-poolId";
    String certificateAuthorityName = "certificate-authority-name";
    String certificateName = "certificate-name";

    createCertificate(
        project, location, poolId, certificateAuthorityName, certificateName, publicKeyBytes);
  }

  // Create a Certificate which is issued by the Certificate Authority present in the CA Pool.
  // The public key used to sign the certificate can be generated using any crypto
  // library/framework.
  public static void createCertificate(
      String project,
      String location,
      String poolId,
      String certificateAuthorityName,
      String certificateName,
      ByteString publicKeyBytes)
      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()) {

      // commonName: Enter a title for your certificate.
      // orgName: Provide the name of your company.
      // domainName: List the fully qualified domain name.
      // certificateLifetime: The validity of the certificate in seconds.
      String commonName = "commonname";
      String orgName = "orgname";
      String domainName = "dns.example.com";
      long certificateLifetime = 1000L;

      // Set the Public Key and its format.
      PublicKey publicKey =
          PublicKey.newBuilder().setKey(publicKeyBytes).setFormat(KeyFormat.PEM).build();

      SubjectConfig subjectConfig =
          SubjectConfig.newBuilder()
              // Set the common name and org name.
              .setSubject(
                  Subject.newBuilder().setCommonName(commonName).setOrganization(orgName).build())
              // Set the fully qualified domain name.
              .setSubjectAltName(SubjectAltNames.newBuilder().addDnsNames(domainName).build())
              .build();

      // Set the X.509 fields required for the certificate.
      X509Parameters x509Parameters =
          X509Parameters.newBuilder()
              .setKeyUsage(
                  KeyUsage.newBuilder()
                      .setBaseKeyUsage(
                          KeyUsageOptions.newBuilder()
                              .setDigitalSignature(true)
                              .setKeyEncipherment(true)
                              .setCertSign(true)
                              .build())
                      .setExtendedKeyUsage(
                          ExtendedKeyUsageOptions.newBuilder().setServerAuth(true).build())
                      .build())
              .setCaOptions(CaOptions.newBuilder().setIsCa(true).buildPartial())
              .build();

      // Create certificate.
      Certificate certificate =
          Certificate.newBuilder()
              .setConfig(
                  CertificateConfig.newBuilder()
                      .setPublicKey(publicKey)
                      .setSubjectConfig(subjectConfig)
                      .setX509Config(x509Parameters)
                      .build())
              .setLifetime(Duration.newBuilder().setSeconds(certificateLifetime).build())
              .build();

      // Create the Certificate Request.
      CreateCertificateRequest certificateRequest =
          CreateCertificateRequest.newBuilder()
              .setParent(CaPoolName.of(project, location, poolId).toString())
              .setCertificateId(certificateName)
              .setCertificate(certificate)
              .setIssuingCertificateAuthorityId(certificateAuthorityName)
              .build();

      // Get the Certificate response.
      ApiFuture<Certificate> future =
          certificateAuthorityServiceClient
              .createCertificateCallable()
              .futureCall(certificateRequest);

      Certificate response = future.get();
      // Get the PEM encoded, signed X.509 certificate.
      System.out.println(response.getPemCertificate());
      // To verify the obtained certificate, use this intermediate chain list.
      System.out.println(response.getPemCertificateChainList());
    }
  }
}

Python

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

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

def create_certificate(
    project_id: str,
    location: str,
    ca_pool_name: str,
    ca_name: str,
    certificate_name: str,
    common_name: str,
    domain_name: str,
    certificate_lifetime: int,
    public_key_bytes: bytes,
) -> None:
    """
    Create a Certificate which is issued by the Certificate Authority present in the CA Pool.
    The key used to sign the certificate is created by the Cloud KMS.

    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 a unique name for the CA pool.
        ca_name: the name of the certificate authority which issues the certificate.
        certificate_name: set a unique name for the certificate.
        common_name: a title for your certificate.
        domain_name: fully qualified domain name for your certificate.
        certificate_lifetime: the validity of the certificate in seconds.
        public_key_bytes: public key used in signing the certificates.
    """

    caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

    # The public key used to sign the certificate can be generated using any crypto library/framework.
    # Also you can use Cloud KMS to retrieve an already created public key.
    # For more info, see: https://cloud.google.com/kms/docs/retrieve-public-key.

    # Set the Public Key and its format.
    public_key = privateca_v1.PublicKey(
        key=public_key_bytes,
        format_=privateca_v1.PublicKey.KeyFormat.PEM,
    )

    subject_config = privateca_v1.CertificateConfig.SubjectConfig(
        subject=privateca_v1.Subject(common_name=common_name),
        subject_alt_name=privateca_v1.SubjectAltNames(dns_names=[domain_name]),
    )

    # Set the X.509 fields required for the certificate.
    x509_parameters = privateca_v1.X509Parameters(
        key_usage=privateca_v1.KeyUsage(
            base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions(
                digital_signature=True,
                key_encipherment=True,
            ),
            extended_key_usage=privateca_v1.KeyUsage.ExtendedKeyUsageOptions(
                server_auth=True,
                client_auth=True,
            ),
        ),
    )

    # Create certificate.
    certificate = privateca_v1.Certificate(
        config=privateca_v1.CertificateConfig(
            public_key=public_key,
            subject_config=subject_config,
            x509_config=x509_parameters,
        ),
        lifetime=duration_pb2.Duration(seconds=certificate_lifetime),
    )

    # Create the Certificate Request.
    request = privateca_v1.CreateCertificateRequest(
        parent=caServiceClient.ca_pool_path(project_id, location, ca_pool_name),
        certificate_id=certificate_name,
        certificate=certificate,
        issuing_certificate_authority_id=ca_name,
    )
    result = caServiceClient.create_certificate(request=request)

    print("Certificate creation result:", result)

기존 Cloud KMS 키를 사용하여 인증서 요청

Cloud KMS 키를 사용하여 종단 개체 서버 TLS 인증서를 만들려면 다음 명령어를 실행합니다.

gcloud privateca certificates create \
  --issuer-pool POOL_ID \
  --kms-key-version projects/PROJECT_ID/locations/LOCATION_ID/keyRings/KEY_RING/cryptoKeys/KEY/cryptoKeyVersions/KEY_VERSION \
  --cert-output-file CERT_FILENAME \
  --dns-san "DNS_NAME" \
  --use-preset-profile "leaf_server_tls"

다음을 바꿉니다.

  • POOL_ID: CA 풀의 이름입니다.
  • PROJECT_ID: 프로젝트 ID
  • LOCATION_ID: 키링의 위치입니다.
  • KEY_RING: 키가 있는 키링의 이름입니다.
  • KEY: 키 이름입니다.
  • KEY_VERSION: 키의 버전입니다.
  • CERT_FILENAME: PEM으로 인코딩된 인증서 체인 파일의 경로입니다. 인증서 체인 파일은 최종 항목에서 루트로 정렬됩니다.
  • DNS_NAME: 쉼표로 구분된 DNS SAN입니다.

인증서로 일반적인 작업 수행

이 섹션에서는 인증서로 일반적인 작업을 수행하는 방법을 설명합니다.

CA 풀의 특정 CA에서 인증서 발급

gcloud

인증서 발급을 위해 CA 풀에서 특정 CA를 타겟팅하려면 인증서를 발급해야 하는 CA의 CA_ID와 함께 --ca 플래그를 추가합니다.

gcloud privateca certificates create \
  --issuer-pool POOL_ID \
  --ca CA_ID \
  --generate-key \
  --key-output-file KEY_FILENAME \
  --cert-output-file CERT_FILENAME \
  --dns-san "DNS_NAME" \
  --use-preset-profile "leaf_server_tls"

콘솔

Google Cloud 콘솔에서는 특정 CA의 인증서 발급만 지원합니다. 자동 생성된 키를 사용하여 인증서 요청 섹션 또는 CSR을 사용하여 인증서 요청 섹션의 안내에 따라 인증서를 발급해야 하는 CA를 선택합니다.

Terraform

resource "google_privateca_certificate_authority" "authority" {
  // 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-sample-certificate-authority"
  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
      }
      key_usage {
        base_key_usage {
          digital_signature = true
          cert_sign         = true
          crl_sign          = true
        }
        extended_key_usage {
          server_auth = true
        }
      }
    }
  }
  lifetime = "86400s"
  key_spec {
    algorithm = "RSA_PKCS1_4096_SHA256"
  }
}

resource "google_privateca_certificate" "default" {
  pool     = "my-pool"
  location = "us-central1"
  lifetime = "860s"
  name     = "my-sample-certificate"
  config {
    subject_config {
      subject {
        common_name         = "san1.example.com"
        country_code        = "us"
        organization        = "google"
        organizational_unit = "enterprise"
        locality            = "mountain view"
        province            = "california"
        street_address      = "1600 amphitheatre parkway"
        postal_code         = "94109"
      }
    }
    x509_config {
      ca_options {
        is_ca = false
      }
      key_usage {
        base_key_usage {
          crl_sign = true
        }
        extended_key_usage {
          server_auth = true
        }
      }
    }
    public_key {
      format = "PEM"
      key    = base64encode(data.tls_public_key.example.public_key_pem)
    }
  }
  // Certificates require an authority to exist in the pool, though they don't
  // need to be explicitly connected to it
  depends_on = [google_privateca_certificate_authority.authority]
}

resource "tls_private_key" "example" {
  algorithm = "RSA"
}

data "tls_public_key" "example" {
  private_key_pem = tls_private_key.example.private_key_pem
}

발급된 인증서 보기

콘솔

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

    Certificate Authority Service로 이동

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

  3. 인증 기관 페이지에서 CA의 이름을 클릭합니다.

  4. 인증 기관 세부정보 페이지 하단에서 발급된 인증서 보기를 클릭하여 CA에서 발급한 인증서 목록을 확인합니다.

    모든 인증서 페이지에서 인증서를 볼 수 있습니다. 세부정보에는 인증서 상태, CA 발급, CA가 포함된 CA 풀, 인증서 만료일 등이 포함됩니다.

gcloud

CA 풀의 특정 CA에서 발급한 모든 인증서를 나열하려면 다음 gcloud 명령어를 사용합니다.

gcloud privateca certificates list --issuer-pool ISSUER_POOL --ca CA_NAME

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

특정 위치의 모든 CA에 있는 모든 인증서를 나열하려면 다음 gcloud 명령어를 사용합니다.

gcloud privateca certificates list --location LOCATION

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

// List Certificates present in the given CA pool.
func listCertificates(
	w io.Writer,
	projectId string,
	location string,
	caPoolId 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 CA Pool id in which the certificate exists.

	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", projectId, location, caPoolId)

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

	it := caClient.ListCertificates(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("unable to get the list of cerficates: %w", err)
		}

		fmt.Fprintf(w, " - %s (common name: %s)", resp.Name,
			resp.CertificateDescription.SubjectDescription.Subject.CommonName)
	}

	return nil
}

Java

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


import com.google.cloud.security.privateca.v1.CaPoolName;
import com.google.cloud.security.privateca.v1.Certificate;
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
import java.io.IOException;

public class ListCertificates {

  public static void main(String[] args) throws 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: Id of the CA pool which contains the certificates to be listed.
    String project = "your-project-id";
    String location = "ca-location";
    String poolId = "ca-pool-id";
    listCertificates(project, location, poolId);
  }

  // List Certificates present in the given CA pool.
  public static void listCertificates(String project, String location, String poolId)
      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 `certificateAuthorityServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (CertificateAuthorityServiceClient certificateAuthorityServiceClient =
        CertificateAuthorityServiceClient.create()) {

      CaPoolName caPool =
          CaPoolName.newBuilder()
              .setProject(project)
              .setLocation(location)
              .setCaPool(poolId)
              .build();

      // Retrieve and print the certificate names.
      System.out.println("Available certificates: ");
      for (Certificate certificate :
          certificateAuthorityServiceClient.listCertificates(caPool).iterateAll()) {
        System.out.println(certificate.getName());
      }
    }
  }
}

Python

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


import google.cloud.security.privateca_v1 as privateca_v1

def list_certificates(
    project_id: str,
    location: str,
    ca_pool_name: str,
) -> None:
    """
    List Certificates present in the given CA 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: name of the CA pool which contains the certificates to be listed.
    """

    caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

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

    # Retrieve and print the certificate names.
    print(f"Available certificates in CA pool {ca_pool_name}:")
    for certificate in caServiceClient.list_certificates(parent=ca_pool_path):
        print(certificate.name)

단일 인증서의 세부정보 보기

콘솔

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

    Certificate Authority Service로 이동

  2. CA 관리자 탭에서 대상 CA를 선택합니다.

  3. CA 이름을 클릭합니다.

  4. 인증 기관 세부정보 페이지 하단에서 발급된 인증서 보기를 클릭하여 발급된 인증서 목록을 확인합니다.

  5. 다운로드하려는 인증서의 작업 열에서 를 클릭합니다.

  6. 다운로드에서 인증서를 클릭합니다. 인증서 체인을 클릭하여 인증서 체인을 다운로드할 수 있습니다.

gcloud

인증서의 전체 설명을 확인하려면 다음 명령어를 실행합니다.

gcloud privateca certificates describe CERT_NAME \
    --issuer-pool POOL_ID

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

PEM으로 인코딩된 X.509 인증서 체인을 파일로 내보내려면 다음 명령어를 실행합니다.

gcloud privateca certificates export CERT_NAME \
    --issuer-pool POOL_ID \
    --include-chain \
    --output-file certificate-file

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

인증서 소유 증명

공개 키 소유 증명은 인증서 요청자가 해당 인증서의 비공개 키를 보유하는지 확인합니다. CA Service는 요청자가 RFC 2986에 따라 PKCS #10 CSR을 제공하는 경우에만 소유 증명을 확인합니다. CertificateConfig의 요청과 같은 다른 형식의 인증서 요청에 대한 소유 증명은 적용되지 않습니다.

인증서 소유자가 해당 인증서의 비공개 키를 소유하고 있는지 여부를 확인하는 것은 인증서를 수락하는 클라이언트 응용 프로그램의 책임입니다. 인증서 발급 중 소유 증명 확인을 적용하는 것은 오작동하는 클라이언트로부터 보호하기 위한 심층 방어의 한 형태입니다. 이러한 클라이언트의 존재는 CA가 소유 증명을 확인하는지 여부와 관계없이 보안 취약점이 될 수 있습니다.

다음 단계