Root-Zertifizierungsstelle erstellen

Auf dieser Seite wird beschrieben, wie Sie eine Stammzertifizierungsstelle in einem CA-Pool erstellen.

Eine Root-Zertifizierungsstelle befindet sich an der Spitze einer Public-Key-Infrastruktur-Hierarchie (PKI) und ist für die Bildung des Trust Anchors der PKI verantwortlich. Damit ein Gerät, eine Software oder eine Komponente ordnungsgemäß an einer PKI teilnehmen und Zertifikate in einer PKI verwenden kann, muss es der PKI vertrauen. Dazu wird das Gerät, die Software oder die Komponente so konfiguriert, dass sie der Stamm-CA vertraut. Daher wird allen von der Root-Zertifizierungsstelle ausgestellten Zertifikaten vertraut.

Hinweise

Stamm-CA erstellen

Eine Root-Zertifizierungsstelle hat ein selbst signiertes Zertifikat, das Sie an die Vertrauensspeicher Ihrer Clients verteilen müssen. Das Zertifikat der Stamm-CA befindet sich oben in der Zertifikatskette. Keine andere Zertifizierungsstelle kann das CA-Zertifikat widerrufen. Die Zertifikatsperrliste der Stamm-CA gilt nur für die anderen Zertifikate, die von der Stamm-CA ausgestellt wurden, nicht für die Stamm-CA selbst.

Sie können eine Root-CA entweder in einem vorhandenen oder in einem neuen CA-Pool erstellen. In der folgenden Anleitung wird ein vorhandener Pool verwendet.

Console

So erstellen Sie eine Root-CA in einem vorhandenen CA-Pool:

  1. Rufen Sie in derGoogle Cloud Console die Seite Certificate Authority Service auf.

    Zum Certificate Authority Service

  2. Klicken Sie auf den Tab CA Manager.

  3. Klicken Sie auf den Einblendpfeil CA erstellen und wählen Sie dann CA in einem vorhandenen CA-Pool erstellen aus.

CA-Pool auswählen

Wählen Sie einen vorhandenen CA-Pool aus der Liste aus und klicken Sie auf Weiter.

CA-Typ auswählen

  1. Wählen Sie unter Typ die Option Root-CA aus.
  2. Geben Sie im Feld Gültig bis den Zeitraum ein, für den die von der Zertifizierungsstelle ausgestellten Zertifikate gültig sein sollen.
  3. Wählen Sie unter Initialisierter Status den Betriebsstatus der zu erstellenden CA aus.
  4. Klicken Sie auf Weiter.
Name des CA-Antragstellers konfigurieren
  1. Geben Sie im Feld Organisation (O) den Namen Ihres Unternehmens ein.
  2. Optional: Geben Sie im Feld Organisationseinheit die Unterabteilung oder Geschäftseinheit des Unternehmens ein.
  3. Optional: Geben Sie im Feld Ländername (C) einen zweistelligen Ländercode ein.
  4. Optional: Geben Sie im Feld Name des Bundeslands den Namen Ihres Bundeslands ein.
  5. Optional: Geben Sie im Feld Ortsname den Namen Ihrer Stadt ein.
  6. Geben Sie im Feld Allgemeiner CA-Name (CN) den CA-Namen ein.
  7. Klicken Sie auf Weiter.
Größe und Algorithmus von CA-Schlüsseln konfigurieren
  1. Wählen Sie den Schlüsselalgorithmus aus, der Ihren Anforderungen am besten entspricht. Informationen zur Auswahl des geeigneten Schlüsselalgorithmus finden Sie unter Schlüsselalgorithmus auswählen.
  2. Klicken Sie auf Weiter.
CA-Artefakte konfigurieren
  1. Wählen Sie aus, ob Sie einen von Google verwalteten oder einen vom Kunden verwalteten Cloud Storage-Bucket verwenden möchten.
    1. Für einen von Google verwalteten Cloud Storage-Bucket erstellt CA Service einen von Google verwalteten Bucket am selben Standort wie die CA.
    2. Klicken Sie für einen vom Kunden verwalteten Cloud Storage-Bucket auf „Durchsuchen“ und wählen Sie einen der vorhandenen Cloud Storage-Buckets aus.
  2. Klicken Sie auf Weiter.
Labels hinzufügen

Die folgenden Schritte sind optional.

So fügen Sie der CA Labels hinzu:

  1. Klicken Sie auf Element hinzufügen.
  2. Geben Sie im Feld Schlüssel 1 den Labelschlüssel ein.
  3. Geben Sie im Feld Wert 1 den Labelwert ein.
  4. Wenn Sie ein weiteres Label hinzufügen möchten, klicken Sie auf Element hinzufügen. Fügen Sie dann den Labelschlüssel und -wert hinzu, wie in den Schritten 2 und 3 beschrieben.
  5. Klicken Sie auf Weiter.
Einstellungen überprüfen

Prüfen Sie alle Einstellungen sorgfältig und klicken Sie dann auf Fertig, um die Zertifizierungsstelle zu erstellen.

gcloud

  1. Führen Sie den folgenden Befehl aus, um eine neue Root-CA in einem vorhandenen CA-Pool zu erstellen:

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

    Ersetzen Sie Folgendes:

    • ROOT_CA_ID: der Name der CA.
    • LOCATION: der Standort des CA-Pools.
    • POOL_ID: der Name des CA-Pools.
    • KEY_ALGORITHM: Der Algorithmus, der zum Erstellen eines Cloud KMS-Schlüssels verwendet werden soll. Dieses Flag ist optional. Wenn Sie dieses Flag nicht angeben, wird standardmäßig der Schlüsselalgorithmus rsa-pkcs1-4096-sha256 verwendet. Weitere Informationen finden Sie unter --key-algorithm-Flag.

    Standardmäßig wird die CA im Status STAGED erstellt. Fügen Sie das Flag --auto-enable ein, um eine CA standardmäßig zu aktivieren.

    Wenn Sie einen vom Kunden verwalteten Cloud Storage-Bucket zum Veröffentlichen von CA-Zertifikaten und CRLs verwenden möchten, fügen Sie dem Befehl --bucket bucket-name hinzu. Ersetzen Sie bucket-name durch den Namen des Cloud Storage-Bucket.

    Führen Sie den folgenden Befehl aus, um die vollständige Liste der Einstellungen aufzurufen:

    gcloud privateca roots create --help
    

Terraform

Wenn Sie eine Root-Zertifizierungsstelle mit einem Verschlüsselungsschlüssel erstellen möchten, der auf Google Cloud basiert, verwenden Sie die folgende Beispielkonfiguration:

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"
}

Verwenden Sie die folgende Beispielkonfiguration, um eine Root-CA mit einem selbst verwalteten Schlüssel zu erstellen:

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

Richten Sie zur Authentifizierung beim CA Service die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Richten Sie zur Authentifizierung beim CA Service die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Richten Sie zur Authentifizierung beim CA Service die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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. Erstellen Sie eine Stamm-CA.

    HTTP-Methode und URL:

    POST https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/caPools/POOL_ID/certificateAuthorities?certificate_authority_id=ROOT_CA_ID

    JSON-Text anfordern:

    {
    "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"
    }
    }
    

    Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

    Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

    {
      "name": "projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID",
      "metadata": {...},
      "done": false
    }
    

  2. Fragen Sie den Vorgang ab, bis er abgeschlossen ist.

    HTTP-Methode und URL:

    GET https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID

    Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

    Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

    {
     "name": "projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID",
     "metadata": {...},
     "done": true,
     "response": {
       "@type": "type.googleapis.com/google.cloud.security.privateca.v1.CertificateAuthority",
       "name": "...",
     }
    }
    

Nachdem Sie bestätigt haben, dass die Zertifizierungsstelle wie erwartet funktioniert, können Sie sie aktivieren, damit sie Load-Balancing-Zertifikate für den CA-Pool ausstellen kann.

Stamm-CA aktivieren

gcloud

Führen Sie den folgenden gcloud-Befehl aus, um eine Stamm-CA zu aktivieren:

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

Ersetzen Sie Folgendes:

  • ROOT_CA_ID: der Name der CA.
  • LOCATION: der Standort des CA-Pools. Eine vollständige Liste der Standorte finden Sie unter Standorte.
  • POOL_ID: der Name des CA-Pools.

Terraform

Wenn Sie eine Stamm-CA mit Terraform erstellen, wird sie bei der Erstellung aktiviert. Wenn Sie eine Stamm-CA im Status STAGED erstellen möchten, legen Sie beim Erstellen der CA das Feld desired_state auf STAGED fest.

Sie können das Feld desired_state nach der Erstellung der CA auf ENABLED oder DISABLED festlegen.

Go

Richten Sie zur Authentifizierung beim CA Service die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Richten Sie zur Authentifizierung beim CA Service die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Richten Sie zur Authentifizierung beim CA Service die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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. Aktivieren Sie die CA, um Zertifikate aus dem CA-Pool auszustellen.

    HTTP-Methode und URL:

    POST https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/caPools/POOL_ID/certificateAuthorities/ROOT_CA_ID:enable

    Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

    Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

    {
        "name": "projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID",
        "metadata": {...},
        "done": false
    }
    

  2. Fragen Sie den Vorgang ab, bis er abgeschlossen ist.

    HTTP-Methode und URL:

    GET https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/operation-UUID

    Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

    Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

    {
        "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 testen

Wenn Sie prüfen möchten, ob eine Zertifizierungsstelle Zertifikate ausstellen kann, fordern Sie ein Zertifikat vom zugehörigen Zertifizierungsstellenpool an und geben Sie mit dem Flag --ca explizit den Namen der Zertifizierungsstelle an, die Sie testen möchten.

Sie können ein Zertifikat aus einem CA-Pool mit den folgenden Methoden anfordern:

  1. Lassen Sie von CA Service einen privaten oder öffentlichen Schlüssel für sich erstellen.
  2. Generieren Sie Ihren eigenen privaten oder öffentlichen Schlüssel und senden Sie eine Anfrage für die Signierung des Zertifikats (Certificate Signing Request, CSR).

Es ist einfacher, einen automatisch generierten privaten oder öffentlichen Schlüssel zu verwenden, um ein Zertifikat von einer Zertifizierungsstelle in einem CA-Pool anzufordern. In diesem Abschnitt finden Sie Informationen zum Testen einer CA mit dieser Methode.

Wenn Sie einen automatisch generierten privaten oder öffentlichen Schlüssel verwenden möchten, um ein Zertifikat von einer Zertifizierungsstelle in einem CA-Pool anzufordern, führen Sie den folgenden gcloud-Befehl aus:

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

Ersetzen Sie Folgendes:

  • POOL_ID: der Name des CA-Pools.
  • ISSUER_LOCATION: Der Speicherort der Zertifizierungsstelle (Certificate Authority, CA), die das digitale Zertifikat ausgestellt hat.
  • ROOT_CA_ID: die eindeutige Kennung der CA, die Sie testen möchten.
  • KEY_FILENAME: Die Datei, in die der generierte Schlüssel im PEM-Format geschrieben wird.
  • CERT_FILENAME: Die Datei, in die die resultierende PEM-codierte Zertifikatskettendatei geschrieben wird. Die Reihenfolge der Zertifikatskette ist vom Blatt zum Stamm.
  • DNS_NAME: Ein oder mehrere durch Kommas getrennte alternative DNS-Antragstellernamen (Subject Alternative Names, SANs).

    Mit dem Flag --generate-key wird ein neuer privater RSA-2048-Schlüssel auf Ihrem Computer generiert.

Wenn Sie ein Zertifikat mit einer Zertifikatsignierungsanfrage (Certificate Signing Request, CSR) von einer Zertifizierungsstelle in einem CA-Pool anfordern möchten oder weitere Informationen zum Anfordern von Zertifikaten benötigen, lesen Sie den Abschnitt Zertifikat anfordern und ausgestellte Zertifikate ansehen.

Zertifizierungsstellen klonen

Führen Sie den folgenden Befehl aus, um eine vorhandene Zertifizierungsstelle zu klonen, um sie zu erneuern, oder um eine neue Zertifizierungsstelle mit derselben Konfiguration zu erstellen:

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

Ersetzen Sie Folgendes:

  • NEW_CA_ID: Die eindeutige Kennung der neuen CA.
  • LOCATION: der Standort des CA-Pools.
  • POOL_ID: der Name des CA-Pools, in dem Sie die neue CA erstellen möchten.
  • EXISTING_CA_ID: Die ID der Quell-CA oder die voll qualifizierte Kennzeichnung für die Quell-CA.

Das Flag --from-ca wird für die Erstellung von Stamm- und untergeordneten CAs unterstützt. Die vorhandene CA muss sich im selben CA-Pool wie die neue CA befinden.

Mit dem Flag --key-algorithm wird die gesamte CA-Konfiguration aus der vorhandenen CA kopiert (mit Ausnahme der Cloud KMS-Schlüsselversion und des Cloud Storage-Bucket). Sie können jedoch weiterhin alle Konfigurationswerte in der neuen CA überschreiben, indem Sie das entsprechende Flag explizit angeben. Sie können beispielsweise weiterhin `--subject SUBJECT angeben, um ein neues Thema zu verwenden.

Wenn Sie das Flag --key-algorithm weglassen, wird standardmäßig der folgende Algorithmus verwendet:

  • rsa-pkcs1-4096-sha256 für Stamm-CAs.
  • rsa-pkcs1-2048-sha256 für untergeordnete CAs.

Weitere Informationen zu diesem gcloud-Befehl finden Sie unter gcloud privateca roots create.

Nächste Schritte