建立根憑證授權單位

本頁說明如何在 CA 集區中建立根憑證授權單位 (CA)。

根層級 CA 位於公用金鑰基礎架構 (PKI) 階層的頂端,負責形成 PKI 的信任錨點。如要正確參與 PKI 並使用憑證,裝置、軟體或元件必須信任 PKI。方法是將裝置、軟體或元件設定為信任根 CA。因此,根 CA 核發的所有憑證都會受到信任。

事前準備

建立根 CA

根 CA 具有自行簽署的憑證,您必須將該憑證發布至用戶端的信任存放區。根 CA 的憑證位於憑證鏈頂端。其他 CA 無法撤銷 CA 憑證。根 CA 的 CRL 只適用於根 CA 核發的其他憑證,不適用於根 CA 本身。

您可以在現有或新的 CA 集區中建立根 CA。下列操作說明使用現有集區。

控制台

如要在現有的 CA 集區中建立根 CA,請按照下列步驟操作:

  1. 前往Google Cloud 控制台的「Certificate Authority Service」(憑證授權單位服務) 頁面。

    前往憑證授權單位服務

  2. 按一下「CA 管理員」分頁標籤。

  3. 按一下「Create CA」(建立 CA) 展開箭頭,然後選取「Create CA in an existing CA pool」(在現有的 CA 集區中建立 CA)

選取 CA 集區

從清單中選取現有的 CA 集區,然後按一下「繼續」

選取 CA 類型

  1. 在「Type」(類型) 下方,選取「Root CA」(根 CA)
  2. 在「Valid for」欄位中,輸入您希望 CA 憑證核發的憑證有效期限。
  3. 在「Initialized state」(初始狀態) 下方,選取要建立憑證授權單位的作業狀態。
  4. 按一下「繼續」
設定 CA 主體名稱
  1. 在「Organization (O)」(機構 (O)) 欄位中,輸入貴公司名稱。
  2. 選用:在「機構單位 (OU)」欄位中,輸入公司部門或業務單位。
  3. 選用:在「Country name (C)」(國家/地區名稱 (C)) 欄位中,輸入兩個英文字母的國家/地區代碼。
  4. 選用:在「州/省名稱」欄位中,輸入您所在州/省的名稱。
  5. 選用:在「Locality name」(所在地名稱) 欄位中輸入城市名稱。
  6. 在「CA common name (CN)」(CA 一般名稱 (CN)) 欄位中,輸入 CA 名稱。
  7. 按一下「繼續」
設定 CA 金鑰大小和演算法
  1. 請選擇最符合需求的金鑰演算法。如要瞭解如何決定合適的金鑰演算法,請參閱「選擇金鑰演算法」。
  2. 按一下「繼續」
設定 CA 構件
  1. 選擇要使用 Google 代管或客戶代管的 Cloud Storage 值區。
    1. 如果是 Google 管理的 Cloud Storage 值區,CA 服務會在與 CA 相同的位置建立 Google 管理的值區。
    2. 如果是客戶代管的 Cloud Storage 值區,請按一下「瀏覽」,然後選取現有的 Cloud Storage 值區。
  2. 按一下「繼續」
新增標籤

下列步驟為選用步驟。

如要為 CA 新增標籤,請按照下列步驟操作:

  1. 按一下「新增項目」
  2. 在「Key 1」欄位中,輸入標籤鍵。
  3. 在「Value 1」(值 1) 欄位中輸入標籤值。
  4. 如要新增其他標籤,請按一下「新增項目」。然後,按照步驟 2 和 3 所述,新增標籤鍵和值。
  5. 按一下「繼續」
檢查設定

詳閱所有設定,然後按一下「完成」建立 CA。

gcloud

  1. 如要在現有的 CA 集區中建立新的根 CA,請執行下列指令:

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

    更改下列內容:

    • ROOT_CA_ID:CA 的名稱。
    • LOCATION:CA 集區的位置。
    • POOL_ID:CA 集區的名稱。
    • KEY_ALGORITHM:用於建立 Cloud KMS 金鑰的演算法。這個標記是選用的,如未加入此標記,金鑰演算法預設為 rsa-pkcs1-4096-sha256。詳情請參閱 --key-algorithm 標記

    根據預設,CA 會建立在 STAGED 狀態。如要預設啟用 CA,請加入 --auto-enable 旗標。

    如要使用客戶管理的 Cloud Storage 值區發布 CA 憑證和 CRL,請在指令中加入 --bucket bucket-name。請將 bucket-name 改成 Cloud Storage bucket 名稱。

    如要查看完整的設定清單,請執行下列指令:

    gcloud privateca roots create --help
    

Terraform

如要使用 Google 擁有及管理的 加密金鑰建立根 CA,請使用下列設定範例:

resource "google_privateca_certificate_authority" "root_ca" {
  // 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-root"
  location                               = "us-central1"
  deletion_protection                    = false # set to true to prevent destruction of the resource
  ignore_active_certificates_on_deletion = true
  config {
    subject_config {
      subject {
        organization = "ACME"
        common_name  = "my-certificate-authority"
      }
    }
    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 {
        }
      }
    }
  }
  key_spec {
    algorithm = "RSA_PKCS1_4096_SHA256"
  }
  // valid for 10 years
  lifetime = "${10 * 365 * 24 * 3600}s"
}

如要使用自行管理的金鑰建立根 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 服務進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 服務進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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 服務進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 方法和網址:

    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 方法和網址:

    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

gcloud

如要啟用根 CA,請執行下列 gcloud 指令:

gcloud privateca roots enable ROOT_CA_ID --location=LOCATION --pool=POOL_ID

更改下列內容:

  • ROOT_CA_ID:CA 的名稱。
  • LOCATION:CA 集區的位置。如需完整的位置清單,請參閱「位置」。
  • POOL_ID:CA 集區的名稱。

Terraform

如果您使用 Terraform 建立根 CA,系統會在建立時啟用根 CA。如要在 STAGED 狀態下建立根 CA,請在建立 CA 時將 desired_state 欄位設為 STAGED

建立 CA 後,您可以將 desired_state 欄位設為 ENABLEDDISABLED

Go

如要向 CA 服務進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 服務進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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 服務進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 方法和網址:

    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 方法和網址:

    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 \
    --issuer-location=ISSUER_LOCATION \
    --ca=ROOT_CA_ID \
    --generate-key \
    --key-output-file=KEY_FILENAME \
    --cert-output-file=CERT_FILENAME \
    --dns-san=DNS_NAME

更改下列內容:

  • POOL_ID:CA 集區的名稱。
  • ISSUER_LOCATION:核發數位憑證的憑證授權單位 (CA) 位置。
  • ROOT_CA_ID:要測試的 CA 專屬 ID。
  • KEY_FILENAME:以 PEM 格式寫入所產生金鑰的檔案。
  • CERT_FILENAME:結果 PEM 編碼憑證鏈結檔案的寫入位置。憑證鏈結的順序為從分葉到根。
  • DNS_NAME:一或多個以半形逗號分隔的 DNS 主體別名 (SAN)。

    --generate-key 旗標會在您的電腦上產生新的 RSA-2048 私密金鑰。

如要使用憑證簽署要求 (CSR) 向 CA 集區中的 CA 要求憑證,或進一步瞭解如何要求憑證,請參閱「要求憑證並查看已核發的憑證」。

複製憑證授權單位

如要複製現有 CA 來續約,或建立具有相同設定的新 CA,請執行下列指令:

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

更改下列內容:

  • NEW_CA_ID:新 CA 的專屬 ID。
  • LOCATION:CA 集區的位置。
  • POOL_ID:要建立新 CA 的 CA 集區名稱。
  • EXISTING_CA_ID:來源 CA 的 ID 或來源 CA 的完整 ID。

--from-ca 旗標支援建立根 CA 和從屬 CA。現有 CA 必須與新 CA 位於相同 CA 集區。

--key-algorithm 旗標會從現有 CA 複製所有 CA 設定 (Cloud KMS 金鑰版本和 Cloud Storage bucket 除外)。不過,您仍可明確提供適當的旗標,覆寫新 CA 中的任何設定值。舉例來說,您仍可指定 `--subject SUBJECT 來使用新主旨。

如果省略 --key-algorithm 標記,演算法預設會使用:

  • rsa-pkcs1-4096-sha256
  • rsa-pkcs1-2048-sha256,適用於從屬 CA。

如要進一步瞭解這個 gcloud 指令,請參閱 gcloud privateca roots create

後續步驟