ルート認証局の作成

このページでは、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. Cloud Storage バケットへの証明書失効リスト(CRL)と CA 証明書の公開を無効にするかどうかを選択します。
  4. Cloud Storage バケットでの CRL と CA 証明書の公開は、デフォルトで有効になっています。これらの設定を無効にするには、切り替えボタンをクリックします。

  5. [次へ] をクリックします。
ラベルを追加する

次の手順は省略可能です。

CA にラベルを追加する場合は、次の手順を行います。

  1. [項目を追加] をクリックします。
  2. [キー 1] フィールドにラベルキーを入力します。
  3. [値 1] フィールドにラベルの値を入力します。
  4. 別のラベルを追加する場合は、 [項目を追加] をクリックします。次に、手順 2 と 3 で説明したように、ラベルキーと値を追加します。
  5. [次へ] をクリックします。
設定を確認する

すべての設定をよく確認し、[作成] をクリックして CA を作成します。

gcloud

  1. ノードプールを作成するには、次のコマンドを実行します。

    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 が有効になります。ルート CA を STAGED 状態に作成するには、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 サービスに秘密鍵または公開鍵を作成させます。
  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: 1 つ以上のカンマ区切りの 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 と同じ CA プールに存在する必要があります。

--key-algorithm フラグを指定すると、既存の CA からすべての CA 構成がコピーされます(Cloud KMS 鍵バージョンと Cloud Storage バケットを除く)。ただし、適切なフラグを明示的に指定することで、新しい CA の構成値をオーバーライドできます。たとえば、--subject SUBJECT を指定すると、新しいサブジェクトを使用できます。

--key-algorithm フラグを省略した場合、アルゴリズムはデフォルトで次の値に設定されます。

  • rsa-pkcs1-4096-sha256(ルート CA)
  • rsa-pkcs1-2048-sha256(下位 CA)

この gcloud コマンドの詳細については、gcloud privateca roots create をご覧ください。

次のステップ