証明書をリクエストし、発行済み証明書を表示する

このトピックでは、Certificate Authority Service に証明書をリクエストし、発行済みの証明書を表示する方法について説明します。

準備

CA Service 証明書リクエスト元(roles/privateca.certificateRequester)または CA Service 証明書マネージャー(roles/privateca.certificateManager)の IAM ロールがあることを確認します。 CA Service の事前定義された IAM のロールの詳細については、IAM を使用したアクセス制御をご覧ください。

プリンシパルに IAM ロールを付与する方法については、単一のロールを付与するをご覧ください。

概要

証明書は、次の方法でリクエストできます。

  1. 独自の秘密鍵または公開鍵を生成し、証明書署名リクエスト(CSR)を送信します。
  2. CA サービスに秘密鍵または公開鍵を作成させます。
  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. 省略可: [鍵のサイズとアルゴリズムを構成する] で、リストから署名鍵のサイズとアルゴリズムを選択します。この手順をスキップすると、SHASSA-PSS の 2048 ビットの鍵(SHA 256 ダイジェストを使用)が使用されます。署名鍵とアルゴリズムの選択については、鍵アルゴリズムを選択するをご覧ください。
  2. [続行] をクリックします。

署名済み証明書をダウンロードする

  1. 省略可: PEM エンコードされた証明書チェーンをダウンロードするには、[証明書チェーンをダウンロード] をクリックします。
  2. 省略可: 関連付けられた PEM でエンコードされた秘密鍵をダウンロードするには、[秘密鍵をダウンロード] をクリックします。

  3. [完了] をクリックします。

gcloud

自動生成された鍵機能を使用するには、Python Cryptographic Authority(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: 1 つ以上の DNS サブジェクト代替名(SAN)。カンマ区切りで指定します。
  • CERTIFICATE_PROFILE: 証明書プロファイルの一意の識別子。 たとえば、エンドユーザーの TLS には leaf_server_tls を使用します。

gcloud コマンドでは、次のフラグが指定されています。

  • --generate-key: マシン上で新しい RSA-2048 秘密鍵を生成します。

次の任意のフラグの組み合わせを使用することもできます。

  • --dns-san: 1 つ以上のカンマ区切りの DNS SAN を渡すことができます。
  • --ip-san: 1 つ以上のカンマ区切りの IP SAN を渡すことができます。
  • --uri-san: 1 つ以上のカンマ区切りの 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 つの証明書の詳細を表示する

コンソール

  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 が所持証明を確認するかどうかに関係なく、セキュリティの脆弱性を引き起こす可能性があります。

次のステップ