要求取得憑證

本頁說明如何在憑證授權單位服務中建立憑證要求。

您可以使用下列方法申請憑證:

  1. 產生自己的私密或公開金鑰,並提交憑證簽署要求 (CSR)。
  2. 使用 CA 服務自動產生的私密或公開金鑰。
  3. 使用現有的 Cloud Key Management Service (Cloud KMS) 金鑰。

事前準備

  1. 準備 CA 服務環境

  2. 如要取得核發憑證所需的權限,請管理員授予您「CA 服務憑證要求者」(roles/privateca.certificateRequester) 或「CA 服務憑證管理員」(roles/privateca.certificateManager) IAM 角色。

    如要進一步瞭解 CA 服務的預先定義 IAM 角色,請參閱「使用身分與存取權管理功能控管存取權」一文。

    如要瞭解如何將 IAM 角色授予主體,請參閱「授予單一角色」一文。

使用 CSR 要求憑證

如要取得憑證,請產生 CSR,然後使用該 CSR 要求憑證。

產生 CSR

如需如何使用 OpenSSL 產生 CSR 的詳細操作說明,請參閱「如何使用 OpenSSL 產生 CSR」。您也可以在產生 CSR 時,參考下列範例設定檔。

如要使用範例設定檔,請按照下列步驟操作:

  1. 使用下列設定建立名為 csr.cnf 的設定檔。

    cat << EOF > csr.cnf
    [req]
    distinguished_name = req_distinguished_name
    req_extensions = v3_req
    prompt = no
    
    [req_distinguished_name]
    CN = example.com
    
    [v3_req]
    keyUsage = critical, digitalSignature, keyEncipherment
    extendedKeyUsage = serverAuth
    subjectAltName = @alt_names
    
    [alt_names]
    DNS.1 = example.com
    DNS.2 = www.example.com
    EOF
    

    這個範例會產生 2048 位元的 RSA 金鑰 (以密碼加密),以及包含下列項目的對應 CSR:

    • 主體 DN 中的 commonName 屬性
    • subjectAlternativeName 擴充功能
    • keyUsage 擴充功能 (標示為重要)
    • extendedKeyUsage 擴充功能

    視需要修改參數。如要使用 x509v3_config 設定檔格式定義 X.509 憑證和 CSR 的擴充功能,請參閱 OpenSSL 說明文件

  2. 執行下列 openssl 指令,產生 CSR 和對應的私密金鑰:

    openssl req -newkey rsa:2048 -out csr.pem -keyout key.pem -config csr.cnf
    

    這個指令會產生下列檔案:

    • csr.pem:您的 CSR,可提交給 CA
    • key.pem:您的私密金鑰,請妥善保管

    在憑證要求中使用 csr.pem 檔案。

使用 CSR 提交憑證要求

如要使用 CSR 申請憑證,請按照下列步驟操作:

控制台

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

    前往憑證授權單位服務

  2. 按一下「要求憑證」

  3. 選取區域。這個地區必須與您要使用的 CA 集區位於相同地區。

  4. 選取 CA 集區。

  5. 選用:從 CA 集區選取特定 CA。請注意,為核發憑證選擇特定 CA 時,您會對該 CA 產生依附關係,導致 CA 輪替作業更加困難。

  6. 選用:選擇憑證範本。如果您使用憑證範本,請確認憑證範本的政策不會與所選 CA 集區的政策衝突。

  7. 按一下「提供憑證簽署要求 (CSR)」,然後點選「下一步」。系統會顯示憑證詳細資料。

  8. 選用:如要覆寫自動產生的憑證名稱,請在「憑證名稱」欄位中輸入自訂名稱。憑證建立後,您就無法刪除或重複使用憑證名稱。

  9. 選用:如要為憑證選擇自訂效期,請在「Valid for」(效期) 欄位中輸入值。

  10. 複製 CSR 並貼到「Certificate CSR」(憑證 CSR) 方塊中。如要上傳含有 CSR 的檔案,請按一下「瀏覽」,然後選擇檔案。

  11. 按一下「產生憑證」

下載已簽署的憑證

  1. 如要查看產生的憑證,請按一下「查看憑證」,然後按一下「查看」
  2. 如要複製憑證,請按一下 。如要以 .crt 檔案形式下載憑證,請按一下「下載憑證」
  3. 選用:如要下載憑證鏈結,請按一下「下載憑證鏈結」

gcloud

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

更改下列內容:

  • CERT_ID:憑證的專屬 ID。
  • POOL_ID:CA 集區的名稱。
  • ISSUER_LOCATION:憑證位置。
  • CSR_FILENAME:儲存 PEM 編碼 CSR 的檔案。
  • CERT_OUTPUT_FILE:必須寫入 PEM 編碼憑證鏈結檔案的路徑。憑證鏈結的排序方式為從終端實體到根。

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

    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 控制台的「憑證授權單位服務」頁面。

    前往憑證授權單位服務

  2. 按一下「要求憑證」

  3. 選取區域。這個地區必須與您要使用的 CA 集區位於相同地區。

  4. 選取 CA 集區。

  5. 按一下「手動輸入詳細資料」。系統會顯示憑證詳細資料。

  6. (選用) 將自動產生的憑證名稱替換為不重複的自訂名稱。

  7. 選用:如要為憑證選擇自訂效期,請在「Valid for」(效期) 欄位中輸入值。

新增網域名稱

  1. 在「新增網域名稱」下方,於「網域名稱 1」欄位中輸入網域名稱。
  2. 選用:如要新增多個網域名稱,請按一下「新增項目」,然後在「網域名稱 2」欄位中輸入其他網域名稱。

擴充金鑰使用方式

  1. 選用:在「金鑰延伸使用」下方,根據用途選取下列選項:

    • 用戶端 TLS:這些憑證可讓您驗證要求者的身分。
    • 伺服器 TLS:這些憑證可驗證伺服器身分。
  2. 點選「下一步」

設定金鑰大小和演算法

  1. 選用:在「設定金鑰大小和演算法」下方,從清單中選取簽署金鑰大小和演算法。如果略過這個步驟,系統會使用具有 SHA 256 摘要的 RSASSA-PSS 2048 位元金鑰。如要瞭解如何選取簽署金鑰和演算法,請參閱選擇金鑰演算法
  2. 按一下「產生憑證」

下載已簽署的憑證

  1. 如要查看產生的憑證,請按一下「查看憑證」,然後按一下「查看」
  2. 選用:如要下載 PEM 編碼憑證鏈結,請按一下「下載憑證鏈結」
  3. 選用:如要下載相關聯的 PEM 編碼私密金鑰,請按一下「下載私密金鑰」

gcloud

如要使用自動產生金鑰功能,您必須安裝 Python 密碼編譯授權單位 (PyCA) 程式庫。如需安裝 Pyca 密碼編譯程式庫的操作說明,請參閱「安裝 Pyca 密碼編譯程式庫」。

如要建立憑證,請使用下列 gcloud 指令:

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

更改下列內容:

  • POOL_ID:CA 集區的名稱。
  • ISSUER_LOCATION:憑證位置。
  • KEY_FILENAME:必須寫入所產生私密金鑰檔案的路徑。
  • CERT_OUTPUT_FILE:PEM 編碼憑證鏈結檔案的寫入路徑。憑證鏈結的順序為從終端實體到根。
  • DNS_NAME:一或多個以半形逗號分隔的 DNS 主體別名 (SAN)。
  • CERTIFICATE_PROFILE憑證設定檔的專屬 ID。舉例來說,請使用 leaf_server_tls 做為實體伺服器 TLS。

gcloud 指令會提及下列標記:

您也可以任意搭配使用下列標記:

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

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


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

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 金鑰要求憑證

您只能使用 Google Cloud CLI,透過 Cloud KMS 金鑰要求憑證。

gcloud

如要使用 Cloud KMS 金鑰建立實體伺服器 TLS 憑證,請執行下列指令:

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

更改下列內容:

  • POOL_ID:CA 集區的名稱。
  • ISSUER_LOCATION:憑證位置。
  • PROJECT_ID:專案 ID。
  • LOCATION_ID:金鑰環的位置。
  • KEY_RING:金鑰所在金鑰環的名稱。
  • KEY:金鑰名稱。
  • KEY_VERSION:金鑰版本。
  • CERT_OUTPUT_FILE:PEM 編碼憑證鏈結檔案的路徑。憑證鏈結檔案的排序方式為從實體到根。
  • DNS_NAME:以半形逗號分隔的 DNS SAN。

從 CA 集區中的特定 CA 核發憑證

本節說明如何從 CA 集區中的特定 CA 核發憑證。

控制台

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

    前往憑證授權單位服務

  2. 按一下「要求憑證」

  3. 選取區域。這個地區必須與您要使用的 CA 集區位於相同地區。

  4. 選取 CA 集區。

  5. 如要選擇 CA,請按一下「使用這個 CA 集區中的特定 CA」,然後從清單中選取 CA。

  6. 如要選取其他參數,請參閱「使用自動產生的金鑰要求憑證」或「使用 CSR 要求憑證」一節。

gcloud

如要指定 CA 集區中的特定 CA 核發憑證,請新增 --ca 旗標,並提供必須核發憑證的 CA CA_ID

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

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
}

在驗證模式下要求憑證

在驗證模式中要求憑證時,系統會建立未簽署的測試憑證。這個測試憑證並非 PEM 編碼,且不會產生費用。 雖然您無法下載憑證,但可透過假設憑證說明確認是否能使用所選參數成功核發簽署憑證。

如要在驗證模式下申請憑證,請按照下列步驟操作:

控制台

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

    前往憑證授權單位服務

  2. 按一下「要求憑證」

  3. 選取「使用驗證模式來查看假設性憑證說明,而非實際核發已簽署的憑證」

  4. 請按照申請簽署憑證的步驟操作。

後續步驟