Crear certificado con la solicitud de firma de certificados

Emitir un certificado de la autoridad certificadora especificada con una CSR

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

Java

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para 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.Certificate;
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
import com.google.cloud.security.privateca.v1.CreateCertificateRequest;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class CreateCertificateCsr {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // 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 a unique id for the CA pool.
    // certificateAuthorityName: The name of the certificate authority to sign the CSR.
    // certificateName: Set a unique name for the certificate.
    // pemCsr: Set the Certificate Issuing Request in the pem encoded format.
    String project = "your-project-id";
    String location = "ca-location";
    String poolId = "ca-pool-id";
    String certificateAuthorityName = "certificate-authority-name";
    String certificateName = "certificate-name";
    String pemCsr =
        "-----BEGIN CERTIFICATE REQUEST-----\n"
            + "sample-pem-csr-format\n"
            + "-----END CERTIFICATE REQUEST-----";

    createCertificateWithCsr(
        project, location, poolId, certificateAuthorityName, certificateName, pemCsr);
  }

  // Create a Certificate which is issued by the specified Certificate Authority.
  // The certificate details and the public key is provided as a CSR (Certificate Signing Request).
  public static void createCertificateWithCsr(
      String project,
      String location,
      String poolId,
      String certificateAuthorityName,
      String certificateName,
      String pemCsr)
      throws IOException, ExecutionException, InterruptedException {
    // 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()) {
      // certificateLifetime: The validity of the certificate in seconds.
      long certificateLifetime = 1000L;

      // Create certificate with CSR.
      // The pemCSR contains the public key and the domain details required.
      Certificate certificate =
          Certificate.newBuilder()
              .setPemCsr(pemCsr)
              .setLifetime(Duration.newBuilder().setSeconds(certificateLifetime).build())
              .build();

      // Create the Certificate Request.
      // Set the CA which is responsible for creating the certificate with the provided CSR.
      CreateCertificateRequest certificateRequest =
          CreateCertificateRequest.newBuilder()
              .setParent(CaPoolName.of(project, location, poolId).toString())
              .setIssuingCertificateAuthorityId(certificateAuthorityName)
              .setCertificateId(certificateName)
              .setCertificate(certificate)
              .build();

      // Get the certificate response.
      ApiFuture<Certificate> future =
          certificateAuthorityServiceClient
              .createCertificateCallable()
              .futureCall(certificateRequest);

      Certificate certificateResponse = future.get();

      System.out.println("Certificate created successfully : " + certificateResponse.getName());

      // Get the signed certificate and the issuer chain list.
      System.out.println("Signed certificate:\n " + certificateResponse.getPemCertificate());
      System.out.println("Issuer chain list:\n" + certificateResponse.getPemCertificateChainList());
    }
  }
}

Python

Para autenticarte en el servicio de AC, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import google.cloud.security.privateca_v1 as privateca_v1
from google.protobuf import duration_pb2


def create_certificate_csr(
    project_id: str,
    location: str,
    ca_pool_name: str,
    ca_name: str,
    certificate_name: str,
    certificate_lifetime: int,
    pem_csr: str,
) -> None:
    """
    Create a Certificate which is issued by the specified Certificate Authority (CA).
    The certificate details and the public key is provided as a Certificate Signing Request (CSR).
    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 to sign the CSR.
        certificate_name: set a unique name for the certificate.
        certificate_lifetime: the validity of the certificate in seconds.
        pem_csr: set the Certificate Issuing Request in the pem encoded format.
    """

    ca_service_client = 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.

    # Create certificate with CSR.
    # The pem_csr contains the public key and the domain details required.
    certificate = privateca_v1.Certificate(
        pem_csr=pem_csr,
        lifetime=duration_pb2.Duration(seconds=certificate_lifetime),
    )

    # Create the Certificate Request.
    # Set the CA which is responsible for creating the certificate with the provided CSR.
    request = privateca_v1.CreateCertificateRequest(
        parent=ca_service_client.ca_pool_path(project_id, location, ca_pool_name),
        certificate_id=certificate_name,
        certificate=certificate,
        issuing_certificate_authority_id=ca_name,
    )
    response = ca_service_client.create_certificate(request=request)

    print(f"Certificate created successfully: {response.name}")

    # Get the signed certificate and the issuer chain list.
    print(f"Signed certificate: {response.pem_certificate}")
    print(f"Issuer chain list: {response.pem_certificate_chain}")

Terraform

Si deseas obtener más información para aplicar o quitar una configuración de Terraform, consulta los comandos básicos de Terraform. Para obtener más información, consulta la documentación de referencia del proveedor de 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"
  }
}

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.