Create Certificate using Certificate Signing Request

Issue certificate by the specified certificate authority using a CSR.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Java


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 CreateCertificate_CSR {

  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
    // pool_Id: 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 pool_Id = "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, pool_Id, 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 pool_Id,
      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, pool_Id).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

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.