בקשת אישור

בדף הזה מוסבר איך יוצרים בקשה לאישור בשירות Certificate Authority Service.

אפשר לבקש אישור באחת מהדרכים הבאות:

  1. ליצור מפתח פרטי או ציבורי משלכם ולשלוח בקשה לחתימה על אישור (CSR).
  2. שימוש במפתח פרטי או ציבורי שנוצר באופן אוטומטי על ידי CA Service.
  3. שימוש במפתח קיים של Cloud Key Management Service ‏(Cloud KMS).

לפני שמתחילים

  1. הכנת הסביבה ל-CA Service.

  2. כדי לקבל את ההרשאות שנדרשות להנפקת אישורים, צריך לבקש מהאדמין להקצות לכם את התפקיד "מבקש אישורים של שירות CA" ‏(roles/privateca.certificateRequester) או "מנהל אישורים של שירות CA" ‏(roles/privateca.certificateManager) ב-IAM.

    למידע נוסף על התפקידים המוגדרים מראש ב-IAM לשירות CA, קראו את המאמר בקרת גישה באמצעות IAM.

    במאמר הקצאת תפקיד יחיד מוסבר איך מקצים תפקיד IAM לחשבון משתמש.

בקשת אישור באמצעות CSR

כדי לקבל אישור, יוצרים CSR ומשתמשים בו כדי לבקש את האישור.

יצירת ה-CSR

הוראות מפורטות ליצירת CSR באמצעות OpenSSL מופיעות במאמר איך יוצרים CSR באמצעות OpenSSL. אפשר גם להשתמש בקובץ התצורה לדוגמה הבא כקובץ עזר כשיוצרים את ה-CSR.

כדי להשתמש בקובץ התצורה לדוגמה:

  1. יוצרים קובץ תצורה בשם csr.cnf באמצעות ההגדרות הבאות.

    cat << EOF > csr.cnf
    [req]
    distinguished_name = req_distinguished_name
    req_extensions = v3_req
    prompt = no
    
    [req_distinguished_name]
    CN = example.com
    
    [v3_req]
    keyUsage = critical, digitalSignature, keyEncipherment
    extendedKeyUsage = serverAuth
    subjectAltName = @alt_names
    
    [alt_names]
    DNS.1 = example.com
    DNS.2 = www.example.com
    EOF
    

    הדוגמה הזו יוצרת מפתח RSA של 2048 ביטים (מוצפן באמצעות ביטוי סיסמה) ו-CSR תואם שמכיל את הפרטים הבאים:

    • המאפיין commonName ב-DN של הנושא
    • התוסף subjectAlternativeName
    • התוסף keyUsage (מסומן כקריטי)
    • התוסף extendedKeyUsage

    משנים את הפרמטרים לפי הצורך. כדי להשתמש בפורמט קובץ התצורה x509v3_config להגדרת תוספים לאישורי X.509 ולבקשות CSR, עיינו במסמכי התיעוד של OpenSSL.

  2. מריצים את הפקודה הבאה של openssl כדי ליצור CSR ומפתח פרטי תואם:

    openssl req -newkey rsa:2048 -out csr.pem -keyout key.pem -config csr.cnf
    

    הפקודה הזו יוצרת את הקבצים הבאים:

    • ‫csr.pem: ה-CSR שלכם, מוכן לשליחה ל-CA
    • ‫key.pem: המפתח הפרטי שלכם, שצריך לשמור עליו מאובטח

    משתמשים בקובץ csr.pem בבקשת האישור.

שליחת בקשה לאישור באמצעות ה-CSR

כדי לבקש אישור באמצעות ה-CSR, פועלים לפי השלבים הבאים:

המסוף

  1. נכנסים לדף Certificate Authority Service במסוףGoogle Cloud .

    כניסה ל-Certificate Authority Service

  2. לוחצים על בקשת אישור.

  3. בחירת אזור. האזור חייב להיות זהה לאזור של מאגר ה-CA שבו אתם מתכוונים להשתמש.

  4. בוחרים מאגר רשויות להנפקת אישורים (CA).

  5. אופציונלי: בוחרים רשות אישורים ספציפית ממאגר רשויות להנפקת אישורים (CA). חשוב לזכור שכאשר בוחרים רשות אישורים ספציפית להנפקת אישורים, נוצרת תלות ברשות האישורים הזו, וקשה יותר להחליף בין רשויות אישורים.

  6. אופציונלי: בוחרים תבנית לתעודה. אם אתם משתמשים בתבנית אישור, ודאו שכללי המדיניות של תבנית האישור לא מתנגשים עם כללי המדיניות של מאגר ה-CA שנבחר.

  7. לוחצים על Provide Certificate Signing Request (CSR) ואז על Next. פרטי האישור מוצגים.

  8. אופציונלי: כדי להחליף את שם האישור שנוצר באופן אוטומטי, מזינים את השם המותאם אישית בשדה שם האישור. אחרי שיוצרים את האישור, אי אפשר למחוק את השם שלו או להשתמש בו שוב.

  9. אופציונלי: כדי לבחור תקופת תוקף מותאמת אישית לאישור, מזינים את הערך בשדה Valid for.

  10. מעתיקים את ה-CSR ומדביקים אותו בתיבה Certificate CSR. אם רוצים להעלות קובץ שמכיל את ה-CSR, לוחצים על Browse ובוחרים את הקובץ.

  11. לוחצים על יצירת אישור.

הורדת האישור החתום

  1. כדי לראות את האישור שנוצר, לוחצים על View certificate ואז על View.
  2. כדי להעתיק את האישור, לוחצים על . כדי להוריד את האישור כקובץ .crt, לוחצים על Download certificate.
  3. אופציונלי: כדי להוריד את שרשרת האישורים, לוחצים על Download certificate chain.

gcloud

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

מחליפים את מה שכתוב בשדות הבאים:

  • ‫CERT_ID: המזהה הייחודי של האישור
  • ‫POOL_ID: שם מאגר ה-CA
  • ‫ISSUER_LOCATION: המיקום של האישור
  • ‫CSR_FILENAME: הקובץ שבו מאוחסן ה-CSR בקידוד PEM
  • ‫CERT_OUTPUT_FILE: הנתיב שבו צריך לכתוב את קובץ שרשרת האישורים בקידוד PEM. שרשרת האישורים מסודרת מישות הקצה ועד לשורש.

הדגל --validity מגדיר את משך התוקף של האישור. זהו דגל אופציונלי שערך ברירת המחדל שלו הוא 30 ימים.

הדגל --requested-not-before-time מאפשר לציין שעת התחלה מותאמת אישית (not_before_time) לאישור בפורמט ISO 8601. לשם כך נדרש allowRequesterSpecifiedNotBeforeTime במדיניות ההנפקה של מאגר ה-CA המנפיק.

למידע נוסף על הפקודה gcloud privateca certificates create, קראו את המאמר 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"
  }
}

‫API בארכיטקטורת REST

  1. יוצרים בקשה לחתימה על אישור (CSR) בשיטה המועדפת, כמו openssl.

    הנה דוגמה ל-CSR שמקודד ל-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. מבקשים אישור.

    ה-method של ה-HTTP וכתובת ה-URL:

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

    תוכן בקשת JSON:

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

    כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

    אתם אמורים לקבל תגובת JSON שדומה לזו:

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

בקשת אישור באמצעות מפתח שנוצר אוטומטית

המסוף

אתם יכולים להשתמש במסוף Google Cloud כדי ליצור אישורי TLS ללקוח או לשרת.

  1. נכנסים לדף Certificate Authority Service במסוףGoogle Cloud .

    כניסה ל-Certificate Authority Service

  2. לוחצים על בקשת אישור.

  3. בחירת אזור. האזור חייב להיות זהה לאזור של מאגר ה-CA שבו אתם מתכוונים להשתמש.

  4. בוחרים מאגר רשויות להנפקת אישורים (CA).

  5. לוחצים על הזנת פרטים באופן ידני. פרטי האישור מוצגים.

  6. אופציונלי: מחליפים את שם האישור שנוצר אוטומטית בשם ייחודי בהתאמה אישית.

  7. אופציונלי: כדי לבחור תקופת תוקף מותאמת אישית לאישור, מזינים את הערך בשדה Valid for.

הוספת שם דומיין

  1. בקטע הוספת שם דומיין, מזינים שם דומיין בשדה שם דומיין 1.
  2. אופציונלי: אם רוצים להוסיף יותר משם דומיין אחד, לוחצים על הוספת פריט ומזינים שם דומיין נוסף בשדה שם דומיין 2.

שימוש מורחב במפתח

  1. אופציונלי: בקטע שימוש מורחב במפתח, בוחרים אחת מהאפשרויות הבאות בהתאם לתרחיש לדוגמה:

    • אישורי TLS של לקוח: האישורים האלה מאפשרים לאמת את הזהות של מבקש הבקשה.
    • שרת TLS: האישורים האלה מאפשרים לאמת את זהות השרת.
  2. לוחצים על הבא.

הגדרת גודל המפתח והאלגוריתם

  1. אופציונלי: בקטע Configure key size and algorithm, בוחרים את הגודל והאלגוריתם של מפתח החתימה מהרשימה. אם מדלגים על השלב הזה, נעשה שימוש במפתח RSASSA-PSS של 2,048 ביט עם תקציר SHA 256. למידע על בחירת מפתח חתימה ואלגוריתם, ראו בחירת אלגוריתם מפתח.
  2. לוחצים על יצירת אישור.

הורדת האישור החתום

  1. כדי לראות את האישור שנוצר, לוחצים על View certificate ואז על View.
  2. אופציונלי: כדי להוריד את שרשרת האישורים בקידוד PEM, לוחצים על Download certificate chain.
  3. אופציונלי: כדי להוריד את המפתח הפרטי המשויך בקידוד PEM, לוחצים על Download private key.

gcloud

כדי להשתמש בתכונה של מפתח שנוצר אוטומטית, צריך להתקין את הספרייה Python Cryptographic Authority (PyCA). להוראות להתקנת ספריית ההצפנה Pyca, ראו הכללת ספריית ההצפנה Pyca.

כדי ליצור אישור, משתמשים בפקודה הבאה של gcloud:

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

מחליפים את מה שכתוב בשדות הבאים:

  • ‫POOL_ID: שם מאגר ה-CA
  • ‫ISSUER_LOCATION: המיקום של האישור
  • ‫KEY_FILENAME: הנתיב שבו צריך לכתוב את קובץ המפתח הפרטי שנוצר
  • ‫CERT_OUTPUT_FILE: הנתיב שבו צריך לכתוב את קובץ שרשרת האישורים בקידוד PEM. שרשרת האישורים מסודרת מישות הקצה ועד לשורש.
  • ‫DNS_NAME: שם חלופי אחד או יותר של בעלי DNS, מופרדים בפסיקים (SAN)
  • ‫CERTIFICATE_PROFILE: המזהה הייחודי של פרופיל האישור. לדוגמה, משתמשים ב-leaf_server_tls ל-TLS של שרת ישות קצה.

הפקודה gcloud כוללת את הדגלים הבאים:

  • ‫--generate-key: יוצר מפתח פרטי חדש מסוג RSA-2048 במכונה.

אפשר גם להשתמש בכל שילוב של הדגלים הבאים:

  • ‫--dns-san: מאפשר להעביר DNS SAN אחד או יותר, מופרדים בפסיקים.
  • ‫--ip-san: מאפשר להעביר IP SAN אחד או יותר, מופרדים בפסיקים.
  • ‫--uri-san: מאפשר להעביר URI SAN אחד או יותר, מופרדים בפסיקים.
  • ‫--subject: מאפשר להעביר שם X.501 של נושא האישור.
  • ‫--requested-not-before-time: מאפשר לציין שעת התחלה מותאמת אישית (not_before_time) לאישור בפורמט ISO 8601.

למידע נוסף על הפקודה gcloud privateca certificates create, קראו את המאמר gcloud privateca certificates create.

המשך

כדי לבצע אימות ב-CA Service, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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

כדי לבצע אימות ב-CA Service, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


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

כדי לבצע אימות ב-CA Service, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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)

בקשת אישור באמצעות מפתח Cloud KMS קיים

אפשר להשתמש רק ב-Google Cloud CLI כדי לבקש אישורים באמצעות מפתח Cloud KMS.

gcloud

כדי להשתמש במפתח של Cloud KMS ליצירת אישור TLS של שרת ישות קצה, מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • ‫POOL_ID: שם מאגר ה-CA
  • ‫ISSUER_LOCATION: המיקום של האישור
  • ‫PROJECT_ID: מזהה הפרויקט
  • ‫LOCATION_ID: המיקום שבו נמצא אוסף המפתחות
  • ‫KEY_RING: השם של אוסף המפתחות שבו נמצא המפתח
  • ‫KEY: השם של המפתח
  • ‫KEY_VERSION: גרסת המפתח
  • ‫CERT_OUTPUT_FILE: הנתיב של קובץ שרשרת האישורים בקידוד PEM. קובץ שרשרת האישורים מסודר מהישות הסופית ועד לרמה הבסיסית (root).
  • ‫DNS_NAME: רשימה של DNS SANs מופרדים בפסיקים

הנפקת אישור מרשות אישורים ספציפית במאגר רשויות להנפקת אישורים (CA)

בקטע הזה מוסבר איך להנפיק אישורים מרשות אישורים ספציפית במאגר רשויות האישורים.

המסוף

  1. נכנסים לדף Certificate Authority Service במסוףGoogle Cloud .

    כניסה ל-Certificate Authority Service

  2. לוחצים על בקשת אישור.

  3. בחירת אזור. האזור חייב להיות זהה לאזור של מאגר ה-CA שבו אתם מתכוונים להשתמש.

  4. בוחרים מאגר רשויות להנפקת אישורים (CA).

  5. כדי לבחור רשות לאישור, לוחצים על Use a specific CA from this CA pool ובוחרים רשות לאישור מהרשימה.

  6. בוחרים פרמטרים אחרים כמו בקטע בקשת אישור באמצעות מפתח שנוצר אוטומטית או בקטע בקשת אישור באמצעות CSR.

gcloud

כדי להנפיק אישור באמצעות רשות ספציפית להנפקת אישורים (CA) במאגר, מוסיפים את הדגל --ca עם ה-CA_ID של הרשות להנפקת אישורים (CA) שצריכה להנפיק את האישור.

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

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
}

בקשת אישור במצב אימות

בקשת אישור במצב אימות יוצרת אישור בדיקה לא חתום. אישור הבדיקה הזה לא מקודד ב-PEM ואין עליו חיוב. אי אפשר להוריד את האישור, אבל התיאור ההיפותטי של האישור מאפשר לכם לוודא שאתם יכולים להנפיק בהצלחה אישור חתום עם הפרמטרים שבחרתם.

כדי לבקש אישור במצב אימות, פועלים לפי השלבים הבאים:

המסוף

  1. נכנסים לדף Certificate Authority Service במסוףGoogle Cloud .

    כניסה ל-Certificate Authority Service

  2. לוחצים על בקשת אישור.

  3. בוחרים באפשרות Use validation mode for a hypothetical certificate description instead of a signed certificate.

  4. מבצעים את אותם השלבים כמו לבקשת אישור חתום.

המאמרים הבאים