Crear una autoridad de certificación raíz

En esta página se describe cómo crear una autoridad de certificación (CA) raíz en un grupo de CAs.

Una autoridad de certificación raíz se encuentra en la parte superior de una jerarquía de infraestructura de clave pública (PKI) y es responsable de formar el anclaje de confianza de la PKI. Para participar correctamente y usar certificados en una PKI, un dispositivo, un software o un componente debe confiar en la PKI. Para ello, se configura el dispositivo, el software o el componente para que confíe en la AC raíz. Por lo tanto, todos los certificados emitidos por la AC raíz son de confianza.

Antes de empezar

Crear una CA raíz

Una AC raíz tiene un certificado autofirmado que debes distribuir a los almacenes de confianza de tus clientes. El certificado de la AC raíz se encuentra en la parte superior de la cadena de certificados. Ninguna otra AC puede revocar el certificado de la AC. La CRL de la AC raíz solo se aplica a los demás certificados que ha emitido la AC raíz, pero no a sí misma.

Puedes crear una AC raíz en un grupo de ACs que ya tengas o en uno nuevo. En las siguientes instrucciones se usa un grupo ya creado.

Consola

Para crear una AC raíz en un grupo de ACs, sigue estos pasos:

  1. Ve a la página Servicio de autoridad de certificación en la consola deGoogle Cloud .

    Ir al Servicio de Autoridades de Certificación

  2. Haga clic en la pestaña Administrador de autoridades de certificación.

  3. Haz clic en la flecha del menú desplegable Crear AC y, a continuación, selecciona Crear AC en un grupo de ACs.

Seleccionar grupo de autoridades de certificación

Selecciona un grupo de CAs de la lista y haz clic en Continuar.

Seleccionar el tipo de autoridad de certificación

  1. En Type (Tipo), selecciona Root CA (Autoridad de certificación raíz).
  2. En el campo Válido durante, introduce la duración durante la que quieres que sean válidos los certificados emitidos por el certificado de AC.
  3. En Estado inicializado, selecciona el estado operativo de la AC que se va a crear.
  4. Haz clic en Continuar.
Configurar el nombre de sujeto de la autoridad de certificación
  1. En el campo Organización (O), introduce el nombre de tu empresa.
  2. Opcional: En el campo Unidad organizativa (UO), introduce el departamento empresarial o la unidad de negocio.
  3. Opcional: En el campo Nombre del país (C), introduce el código de dos letras del país.
  4. Opcional: En el campo Nombre del estado o de la provincia, introduce el nombre de tu estado.
  5. Opcional: En el campo Nombre de la localidad, introduce el nombre de tu ciudad.
  6. En el campo Nombre común de la autoridad de certificación (NC), introduce el nombre de la autoridad de certificación.
  7. Haz clic en Continuar.
Configurar el tamaño de clave y el algoritmo de la autoridad de certificación
  1. Elige el algoritmo de claves que mejor se adapte a tus necesidades. Para obtener información sobre cómo elegir el algoritmo de claves adecuado, consulta Elegir un algoritmo de claves.
  2. Haz clic en Continuar.
Configurar artefactos de la AC
  1. Elige si quieres usar un segmento de Cloud Storage gestionado por Google o por el cliente.
    1. En el caso de un segmento de Cloud Storage gestionado por Google, CA Service crea un segmento gestionado por Google en la misma ubicación que la CA.
    2. En el caso de un segmento de Cloud Storage gestionado por el cliente, haga clic en Examinar y seleccione uno de los segmentos de Cloud Storage.
  2. Haz clic en Continuar.
Añadir etiquetas

Los siguientes pasos son opcionales.

Si quieres añadir etiquetas a la AC, haz lo siguiente:

  1. Haz clic en Añadir elemento.
  2. En el campo Clave 1, introduce la clave de la etiqueta.
  3. En el campo Valor 1, introduce el valor de la etiqueta.
  4. Si quiere añadir otra etiqueta, haga clic en Añadir elemento. A continuación, añade la clave y el valor de la etiqueta, tal como se indica en los pasos 2 y 3.
  5. Haz clic en Continuar.
Revisa los ajustes

Revisa detenidamente todos los ajustes y haz clic en Hecho para crear la AC.

gcloud

  1. Para crear una CA raíz en un grupo de CAs, ejecuta el siguiente comando:

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

    Haz los cambios siguientes:

    • ROOT_CA_ID: el nombre de la autoridad de certificación.
    • LOCATION: la ubicación del grupo de autoridades de certificación.
    • POOL_ID: el nombre del grupo de autoridades de certificación.
    • KEY_ALGORITHM: algoritmo que se usará para crear una clave de Cloud KMS. Esta marca es opcional. Si no incluyes esta marca, el algoritmo de claves será rsa-pkcs1-4096-sha256 de forma predeterminada. Para obtener más información, consulta la marca --key-algorithm.

    De forma predeterminada, la AC se crea en el estado STAGED. Para habilitar una CA de forma predeterminada, incluye la marca --auto-enable.

    Si quieres usar un segmento de Cloud Storage gestionado por el cliente para publicar certificados de AC y CRLs, añade --bucket bucket-name al comando. Sustituye bucket-name por el nombre del segmento de Cloud Storage.

    Para ver la lista completa de ajustes, ejecuta el siguiente comando:

    gcloud privateca roots create --help
    

Terraform

Para crear una AC raíz con una clave de cifrado y propiedad de Google con tecnología de Google Cloud, usa la siguiente configuración de ejemplo:

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

Para crear una CA raíz con una clave autogestionada, usa la siguiente configuración de ejemplo:

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

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


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

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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)

API REST

  1. Crea una CA raíz.

    Método HTTP y URL:

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

    Cuerpo JSON de la solicitud:

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

    Para enviar tu solicitud, despliega una de estas opciones:

    Deberías recibir una respuesta JSON similar a la siguiente:

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

  2. Consulta el estado de la operación hasta que se haya completado.

    Método HTTP y URL:

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

    Para enviar tu solicitud, despliega una de estas opciones:

    Deberías recibir una respuesta JSON similar a la siguiente:

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

Una vez que hayas verificado que la CA funciona correctamente, puedes habilitarla para que empiece a emitir certificados con equilibrio de carga para el grupo de CAs.

Habilitar una AC raíz

gcloud

Para habilitar una CA raíz, ejecuta el siguiente comando gcloud:

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

Haz los cambios siguientes:

  • ROOT_CA_ID: el nombre de la autoridad de certificación.
  • LOCATION: la ubicación del grupo de autoridades de certificación. Para ver la lista completa de ubicaciones, consulta Ubicaciones.
  • POOL_ID: el nombre del grupo de autoridades de certificación.

Terraform

Si usas Terraform para crear una AC raíz, esta se habilitará al crearla. Para crear una AC raíz en el estado STAGED, defina el campo desired_state en STAGED al crear la AC.

Puedes definir el campo desired_state como ENABLED o DISABLED después de crear la CA.

Go

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


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

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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)

API REST

  1. Permite que la AC emita certificados desde el grupo de ACs.

    Método HTTP y URL:

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

    Para enviar tu solicitud, despliega una de estas opciones:

    Deberías recibir una respuesta JSON similar a la siguiente:

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

  2. Consulta el estado de la operación hasta que se haya completado.

    Método HTTP y URL:

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

    Para enviar tu solicitud, despliega una de estas opciones:

    Deberías recibir una respuesta JSON similar a la siguiente:

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

Probar una CA

Para verificar que una CA puede emitir certificados, solicita un certificado del grupo de CAs asociado y menciona explícitamente el nombre de la CA que quieras probar con la marca --ca.

Puede usar los siguientes métodos para solicitar un certificado de un pool de ACs:

  1. Pedirle al servicio de AC que cree una clave privada o pública.
  2. Genera tu propia clave privada o pública y envía una solicitud de firma de certificado (CSR).

Es más fácil usar una clave privada o pública generada automáticamente para solicitar un certificado a una AC de un grupo de ACs. En esta sección se proporciona información sobre cómo probar una CA con ese método.

Para usar una clave privada o pública generada automáticamente para solicitar un certificado a una AC de un grupo de ACs, ejecuta el siguiente comando 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

Haz los cambios siguientes:

  • POOL_ID: el nombre del grupo de autoridades de certificación.
  • ISSUER_LOCATION: la ubicación de la autoridad de certificación (CA) que emitió el certificado digital.
  • ROOT_CA_ID: identificador único de la CA que quieres probar.
  • KEY_FILENAME: el archivo en el que se escribe la clave generada en formato PEM.
  • CERT_FILENAME: el archivo en el que se escribe el archivo de cadena de certificados codificado en PEM resultante. El orden de la cadena de certificados es de hoja a raíz.
  • DNS_NAME: uno o varios nombres alternativos de asunto (SAN) de DNS separados por comas.

    La marca --generate-key genera una nueva clave privada RSA-2048 en tu máquina.

Para usar una solicitud de firma de certificado (CSR) para solicitar un certificado de una AC en un grupo de ACs o para obtener más información sobre cómo solicitar certificados, consulta Solicitar un certificado y ver los certificados emitidos.

Clonar autoridades de certificación

Para clonar una CA y renovarla, o para crear una CA con la misma configuración, ejecuta el siguiente comando:

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

Haz los cambios siguientes:

  • NEW_CA_ID: identificador único de la nueva CA.
  • LOCATION: la ubicación del grupo de autoridades de certificación.
  • POOL_ID: el nombre del grupo de autoridades de certificación en el que quieras crear la nueva autoridad de certificación.
  • EXISTING_CA_ID: el ID de la AC de origen o el identificador completo de la AC de origen.

El indicador --from-ca se puede usar para crear AC raíces y subordinadas. La CA actual debe estar en el mismo grupo de CAs que la nueva CA.

La marca --key-algorithm copia toda la configuración de la AC de la AC que ya tengas (excepto la versión de la clave de Cloud KMS y el segmento de Cloud Storage). Sin embargo, puede anular cualquiera de los valores de configuración de la nueva AC proporcionando explícitamente la marca adecuada. Por ejemplo, puedes seguir especificando `--subject SUBJECT para usar un nuevo asunto.

Si omites la marca --key-algorithm, el algoritmo se aplicará de forma predeterminada de la siguiente manera:

  • rsa-pkcs1-4096-sha256 para las AC raíces.
  • rsa-pkcs1-2048-sha256 para las ACs subordinadas.

Para obtener más información sobre este comando gcloud, consulta gcloud privateca roots create.

Siguientes pasos