Criar um modelo de certificado que possa ser reutilizado para cenários comuns de emissão de certificados.
Exemplo de código
Java
Para autenticar o serviço de CA, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
import com.google.api.core.ApiFuture;
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
import com.google.cloud.security.privateca.v1.CertificateIdentityConstraints;
import com.google.cloud.security.privateca.v1.CertificateTemplate;
import com.google.cloud.security.privateca.v1.CreateCertificateTemplateRequest;
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.LocationName;
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.type.Expr;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class CreateCertificateTemplate {
public static void main(String[] args)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
/* 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 */
String project = "your-project-id";
String location = "ca-location";
String certificateTemplateId = "certificate-template-id";
createCertificateTemplate(project, location, certificateTemplateId);
}
/* Creates a Certificate template. These templates can be reused for common
certificate issuance scenarios. */
public static void createCertificateTemplate(
String project, String location, String certificateTemplateId)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
/* 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()) {
/* Describes any predefined X.509 values set by this template.
The provided extensions are copied over to certificate requests that use this template.*/
KeyUsage keyUsage =
KeyUsage.newBuilder()
.setBaseKeyUsage(
KeyUsageOptions.newBuilder()
.setDigitalSignature(true)
.setKeyEncipherment(true)
.build())
.setExtendedKeyUsage(ExtendedKeyUsageOptions.newBuilder().setServerAuth(true).build())
.build();
CaOptions caOptions = CaOptions.newBuilder().setIsCa(false).build();
/* CEL expression that is evaluated against the Subject and
Subject Alternative Name of the certificate before it is issued. */
Expr expr =
Expr.newBuilder().setExpression("subject_alt_names.all(san, san.type == DNS)").build();
// Set the certificate issuance schema.
CertificateTemplate certificateTemplate =
CertificateTemplate.newBuilder()
.setPredefinedValues(
X509Parameters.newBuilder().setKeyUsage(keyUsage).setCaOptions(caOptions).build())
.setIdentityConstraints(
CertificateIdentityConstraints.newBuilder()
.setCelExpression(expr)
.setAllowSubjectPassthrough(false)
.setAllowSubjectAltNamesPassthrough(false)
.build())
.build();
// Set the parent and certificate template properties.
CreateCertificateTemplateRequest certificateTemplateRequest =
CreateCertificateTemplateRequest.newBuilder()
.setParent(LocationName.of(project, location).toString())
.setCertificateTemplate(certificateTemplate)
.setCertificateTemplateId(certificateTemplateId)
.build();
// Create Template request.
ApiFuture<Operation> futureCall =
certificateAuthorityServiceClient
.createCertificateTemplateCallable()
.futureCall(certificateTemplateRequest);
Operation response = futureCall.get(60, TimeUnit.SECONDS);
if (response.hasError()) {
System.out.println("Error creating certificate template ! " + response.getError());
return;
}
System.out.println("Successfully created certificate template ! " + response.getName());
}
}
}
Python
Para autenticar o serviço de CA, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
import google.cloud.security.privateca_v1 as privateca_v1
from google.type import expr_pb2
def create_certificate_template(
project_id: str,
location: str,
certificate_template_id: str,
) -> None:
"""
Create a Certificate template. These templates can be reused for common
certificate issuance scenarios.
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.
certificate_template_id: set a unique name for the certificate template.
"""
caServiceClient = privateca_v1.CertificateAuthorityServiceClient()
# Describes any predefined X.509 values set by this template.
# The provided extensions are copied over to certificate requests that use this template.
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,
),
),
ca_options=privateca_v1.X509Parameters.CaOptions(
is_ca=False,
),
)
# CEL expression that is evaluated against the Subject and
# Subject Alternative Name of the certificate before it is issued.
expr = expr_pb2.Expr(expression="subject_alt_names.all(san, san.type == DNS)")
# Set the certificate issuance schema.
certificate_template = privateca_v1.CertificateTemplate(
predefined_values=x509_parameters,
identity_constraints=privateca_v1.CertificateIdentityConstraints(
cel_expression=expr,
allow_subject_passthrough=False,
allow_subject_alt_names_passthrough=False,
),
)
# Request to create a certificate template.
request = privateca_v1.CreateCertificateTemplateRequest(
parent=caServiceClient.common_location_path(project_id, location),
certificate_template=certificate_template,
certificate_template_id=certificate_template_id,
)
operation = caServiceClient.create_certificate_template(request=request)
result = operation.result()
print("Operation result:", result)
Terraform
Para saber como aplicar ou remover uma configuração do Terraform, consulte Comandos básicos do Terraform. Para mais informações, consulte a documentação de referência do provedor Terraform.
resource "google_privateca_certificate_template" "template" {
location = "us-central1"
name = "my-certificate-template"
description = "An updated sample certificate template"
identity_constraints {
allow_subject_alt_names_passthrough = true
allow_subject_passthrough = true
cel_expression {
description = "Always true"
expression = "true"
location = "any.file.anywhere"
title = "Sample expression"
}
}
passthrough_extensions {
additional_extensions {
object_id_path = [1, 6]
}
known_extensions = ["EXTENDED_KEY_USAGE"]
}
predefined_values {
additional_extensions {
object_id {
object_id_path = [1, 6]
}
value = "c3RyaW5nCg=="
critical = true
}
aia_ocsp_servers = ["string"]
ca_options {
is_ca = false
max_issuer_path_length = 6
}
key_usage {
base_key_usage {
cert_sign = false
content_commitment = true
crl_sign = false
data_encipherment = true
decipher_only = true
digital_signature = true
encipher_only = true
key_agreement = true
key_encipherment = true
}
extended_key_usage {
client_auth = true
code_signing = true
email_protection = true
ocsp_signing = true
server_auth = true
time_stamping = true
}
unknown_extended_key_usages {
object_id_path = [1, 6]
}
}
policy_ids {
object_id_path = [1, 6]
}
}
}
resource "google_privateca_certificate_authority" "test_ca" {
pool = "my-pool"
certificate_authority_id = "my-certificate-authority-test-ca"
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-from-template"
pem_csr = tls_cert_request.example.cert_request_pem
certificate_template = google_privateca_certificate_template.template.id
}
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"
}
}
A seguir
Para pesquisar e filtrar amostras de código para outros produtos do Google Cloud, consulte o navegador de amostra do Google Cloud.