Request a certificate and view issued certificates

This topic describes how you can request a certificate from Certificate Authority Service and view the issued certificates.

Before you begin

Make sure you have the CA Service Certificate Requester (roles/privateca.certificateRequester) or the CA Service Certificate Manager (roles/privateca.certificateManager) IAM role. For more information about the predefined IAM roles for CA Service, see Access control with IAM.

For information about granting an IAM role to a principal, see Grant a single role.

Overview

You can request a certificate using the following methods:

  1. Generate your own private or public key and submit a Certificate Signing Request (CSR).
  2. Have CA Service create a private or public key for you.
  3. Use an existing Cloud Key Management Service (Cloud KMS) key.

Request certificate using a CSR

Before you proceed, you must generate a CSR. After generating a CSR, do the following:

Console

  1. Go to the Certificate Authority Service page on the Google Cloud console.

    Go to Certificate Authority Service

  2. Click the CA Manager tab.

  3. Click the name of the CA you want to issue from.

  4. On the bottom of the CA details page, click Request a certificate.

  5. Optional: If you want to use a certificate template, click , select a template from the list, and click Save.

  6. Click Provide CSR.

  7. Optional: To overwrite the automatically generated certificate name, enter the custom name in the Certificate name field.

  8. Optional: To choose a custom validity period for the certificate, enter the value in the Valid for field.

  9. Copy and paste your CSR to the Certificate CSR box. To upload the CSR, click Browse.

  10. Click Next.

Download the signed certificate

  1. To copy the certificate, click . To download the certificate in the form of a .crt file, click Download certificate.
  2. Optional: To download the certificate chain, click Download certificate chain.
  3. Click Done.

gcloud

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

Replace the following:

  • CERT_ID: The unique identifier of the certificate.
  • POOL_ID: The name of the CA pool.
  • CSR_FILENAME: The file that stores the PEM-encoded CSR.

The --validity flag defines the duration the certificate is valid. It is an optional flag whose default value is 30 days.

For more information about the gcloud privateca certificates create command, see 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. Generate a Certificate Signing Request (CSR) using your preferred method, such as openssl.

    The following is a sample CSR that is encoded for JSON.

    -----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. Request a certificate.

    HTTP method and URL:

    POST https://privateca.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/caPools/POOL_ID/certificates?certificate_id=CERTIFICATE_ID

    Request JSON body:

    {
     "lifetime": {
       "seconds": 3600,
       "nanos": 0
     },
     "pem_csr": "PEM_CSR"
    }
    

    To send your request, expand one of these options:

    You should receive a JSON response similar to the following:

    {
     "name": "projects/project-id/locations/location/certificateAuthorities/ca-id/certificates/certificate-id",
     "pemCertificate": "-----BEGIN CERTIFICATE-----...",
     "certificateDescription": {...}
    }
    

Request certificate using an auto-generated key

Console

You can use Google Cloud console to generate client or server TLS certificates.

  1. In the Google Cloud console, go to the Certificate Authority Service page.

    Go to Certificate Authority Service

  2. Click the CA Manager tab.

  3. Click the name of the CA you want to issue from.

  4. At the bottom of the Certificate authority details page, click Request a certificate.

  5. Optional: If you want to use a certificate template, click , select a template from the list, and click Save.

  6. Click Enter details.

  7. Optional: Replace the auto-generated Certificate name with a custom name that is unique.

  8. Optional: To choose a custom validity period for the certificate, enter the value in the Valid for field.

Add domain name

  1. Under Add domain name, enter a domain name in the Domain name 1 field.
  2. Optional: If you want to add more than one domain name, click Add Item, and enter another domain name in the Domain name 2 field.

Extended key usage

  1. Optional: Under Extended key usage, select between the following options based on your use case:

    • Server TLS: These certificates let you authenticate the identity of a server.
    • Client TLS: These certificates let you authenticate the identity of a requester.
  2. Click Next.

Configure the key size and algorithm

  1. Optional: Under Configure key size and algorithm, select the signing key size and algorithm from the list. If you skip this step, RSASSA-PSS 2048 bit key with a SHA 256 digest is used. For information about selecting a signing key and algorithm, see Choose a key algorithm.
  2. Click Continue.

Download the signed certificate

  1. Optional: To download the PEM-encoded certificate chain, click Download certificate chain.
  2. Optional: To download the associated PEM-encoded private key, click Download private key.

  3. Click Done.

gcloud

To use the auto-generated key feature, you need to install the Python Cryptographic Authority (PyCA) library. For instructions about installing the Pyca cryptography library, see Including the Pyca cryptography library.

To create a certificate, use the following gcloud command:

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

Replace the following:

  • POOL_ID: The name of the CA pool.
  • KEY_FILENAME: The path where the generated private key file must be written.
  • CERT_FILENAME: The path where the PEM-encoded certificate chain file must be written. The certificate chain is ordered from end-entity to root.
  • DNS_NAME: One or more comma-separated DNS subject alternative names (SANs).
  • CERTIFICATE_PROFILE: The unique identifier of the certificate profile. For example, use leaf_server_tls for end-entity server TLS.

The gcloud command mentions the following flags:

  • --generate-key: Generates a new RSA-2048 private key on your machine.

You can also use any combination of the following flags:

  • --dns-san: Lets you pass one or more comma-separated DNS SANs.
  • --ip-san: Lets you pass one or more comma-separated IP SANs.
  • --uri-san: Lets you pass one or more comma-separated URI SANs.
  • --subject: Lets you pass an X.501 name of the certificate subject.

For more information about the gcloud privateca certificates create command, see gcloud privateca certificates create.

Go

To authenticate to CA Service, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To authenticate to CA Service, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To authenticate to CA Service, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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)

Request certificate using an existing Cloud KMS key

To use a Cloud KMS key to create an end-entity server TLS certificate, run the following command:

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

Replace the following:

  • POOL_ID: The name of the CA pool.
  • PROJECT_ID: The project ID.
  • LOCATION_ID: The location of the key ring.
  • KEY_RING: The name of the key ring where the key is located.
  • KEY: The name of the key.
  • KEY_VERSION: The version of the key.
  • CERT_FILENAME: The path of the PEM-encoded certificate chain file. The certificate chain file is ordered from end-entity to root.
  • DNS_NAME: Comma-separated DNS SANs.

Performing common operations with certificates

This section describes how you can perform certain common operations with certificates.

Issue a certificate from a specific CA in a CA pool

gcloud

To target a specific CA in the CA pool for certificate issuance, add the --ca flag with the CA_ID of the CA that must issue the certificate.

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

Console

The Google Cloud console only supports certificate issuance from a particular CA. Follow the instructions in the Request certificate using an auto-generated Key section or the Request certificate using a CSR section to choose the CA that must issue the certificate.

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
}

View issued certificates

Console

  1. In the Google Cloud console, go to the Certificate Authority Service page.

    Go to Certificate Authority Service

  2. Click the CA manager tab.

  3. On the Certificate authorities page, click the name of the CA.

  4. At the bottom of the Certificate authority details page, click View issued certificates to view the list of certificates issued by the CA.

    You can see the certificates on the All certificates page. The details include the status of the certificate, issuing CA, the CA pool that contains the CA, the certificate's expiration date, and more.

gcloud

To list all certificates issued by a particular CA in a CA pool, use the following gcloud command:

gcloud privateca certificates list --issuer-pool ISSUER_POOL --ca CA_NAME

For more information about the gcloud privateca certificates list command, see gcloud privateca certificates list.

To list all certificates across all CAs in a given location, use the following gcloud command:

gcloud privateca certificates list --location LOCATION

Go

To authenticate to CA Service, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	privateca "cloud.google.com/go/security/privateca/apiv1"
	"cloud.google.com/go/security/privateca/apiv1/privatecapb"
	"google.golang.org/api/iterator"
)

// List Certificates present in the given CA pool.
func listCertificates(
	w io.Writer,
	projectId string,
	location string,
	caPoolId 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 CA Pool id in which the certificate exists.

	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", projectId, location, caPoolId)

	// Create the ListCertificatesRequest.
	// See https://pkg.go.dev/cloud.google.com/go/security/privateca/apiv1/privatecapb#ListCertificatesRequest.
	req := &privatecapb.ListCertificatesRequest{Parent: fullCaName}

	it := caClient.ListCertificates(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("unable to get the list of cerficates: %w", err)
		}

		fmt.Fprintf(w, " - %s (common name: %s)", resp.Name,
			resp.CertificateDescription.SubjectDescription.Subject.CommonName)
	}

	return nil
}

Java

To authenticate to CA Service, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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 java.io.IOException;

public class ListCertificates {

  public static void main(String[] args) throws 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: Id of the CA pool which contains the certificates to be listed.
    String project = "your-project-id";
    String location = "ca-location";
    String poolId = "ca-pool-id";
    listCertificates(project, location, poolId);
  }

  // List Certificates present in the given CA pool.
  public static void listCertificates(String project, String location, String poolId)
      throws 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()) {

      CaPoolName caPool =
          CaPoolName.newBuilder()
              .setProject(project)
              .setLocation(location)
              .setCaPool(poolId)
              .build();

      // Retrieve and print the certificate names.
      System.out.println("Available certificates: ");
      for (Certificate certificate :
          certificateAuthorityServiceClient.listCertificates(caPool).iterateAll()) {
        System.out.println(certificate.getName());
      }
    }
  }
}

Python

To authenticate to CA Service, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import google.cloud.security.privateca_v1 as privateca_v1


def list_certificates(
    project_id: str,
    location: str,
    ca_pool_name: str,
) -> None:
    """
    List Certificates present in the given CA 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: name of the CA pool which contains the certificates to be listed.
    """

    caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

    ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name)

    # Retrieve and print the certificate names.
    print(f"Available certificates in CA pool {ca_pool_name}:")
    for certificate in caServiceClient.list_certificates(parent=ca_pool_path):
        print(certificate.name)

View details for a single certificate

Console

  1. In the Google Cloud console, go to the Certificate Authority Service page.

    Go to Certificate Authority Service

  2. Pick your target CA under the CA Manager tab.

  3. Click the CA name.

  4. At the bottom of the Certificate authority details page, click View issued certificates to see the list of issued certificates.

  5. Click in the Actions column for the certificate you want to download.

  6. Under Download, click Certificate. You can download the certificate chain by clicking Certificate chain.

gcloud

To see the full description of a certificate, run the following command:

gcloud privateca certificates describe CERT_NAME \
    --issuer-pool POOL_ID

For more information about the gcloud privateca certificates describe command, see gcloud privateca certificates describe.

To export the PEM-encoded X.509 certificate chain and to a file, run the following command:

gcloud privateca certificates export CERT_NAME \
    --issuer-pool POOL_ID \
    --include-chain \
    --output-file certificate-file

For more information about the gcloud privateca certificates export command, see gcloud privateca certificates export.

Proof-of-possession for certificates

Proof-of-possession of the private key ensures that the requester of a certificate holds the private key for that certificate. CA Service checks proof-of-possession only if the requester provides a PKCS #10 CSR according to RFC 2986. Proof-of-possession for other forms of certificate requests, such as requests by CertificateConfig is not enforced.

It is the responsibility of client applications that accept certificates to validate whether the certificate holder possesses the private key of that certificate. Enforcing proof-of-possession checks during certificate issuance is a form of defense-in-depth to protect against misbehaving clients. The existence of such clients, regardless of whether the CA checks proof-of-possession, could constitute a security vulnerability.

What's next