יצירת מפתח

בדף הזה מוסבר איך ליצור מפתח ב-Cloud KMS. מפתח יכול להיות מפתח הצפנה סימטרי או אסימטרי, מפתח חתימה אסימטרי או מפתח חתימה של MAC.

כשיוצרים מפתח, מוסיפים אותו לאוסף מפתחות במיקום ספציפי ב-Cloud KMS. אפשר ליצור מחזיק מפתחות חדש או להשתמש במחזיק מפתחות קיים. בדף הזה יוצרים מפתח חדש של Cloud KMS או Cloud HSM ומוסיפים אותו לאוסף מפתחות קיים. ‫ כדי ליצור מפתח Cloud EKM, אפשר לעיין במאמר יצירת מפתח חיצוני. הוראות לייבוא מפתח של Cloud KMS או Cloud HSM מופיעות במאמר ייבוא מפתח.

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

לפני שמבצעים את המשימות בדף הזה, צריך:

  1. משאב פרויקט Google Cloud שיכיל את משאבי Cloud KMS. מומלץ להשתמש בפרויקט נפרד למשאבי Cloud KMS שלא מכיל משאבי Google Cloud אחרים.
  2. השם והמיקום של אוסף המפתחות שבו רוצים ליצור את המפתח. בוחרים מחזיק מפתחות במיקום שקרוב למשאבים האחרים ותומך ברמת ההגנה שבחרתם. כדי לראות את המיקומים הזמינים ואת רמות ההגנה שהם תומכים בהן, אפשר לעיין במאמר בנושא מיקומים של Cloud KMS. כדי ליצור אוסף מפתחות, אפשר לעיין במאמר יצירת אוסף מפתחות.
  3. אופציונלי: כדי להשתמש ב-CLI של gcloud, צריך להכין את הסביבה.

    במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

התפקידים הנדרשים

כדי לקבל את ההרשאות שדרושות ליצירת מפתחות, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט או במשאב אב:

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

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

ההרשאות הנדרשות

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

  • cloudkms.cryptoKeys.create
  • cloudkms.cryptoKeys.get
  • cloudkms.cryptoKeys.list
  • cloudkms.cryptoKeyVersions.create
  • cloudkms.cryptoKeyVersions.get
  • cloudkms.cryptoKeyVersions.list
  • cloudkms.keyRings.get
  • cloudkms.keyRings.list
  • cloudkms.locations.get
  • cloudkms.locations.list
  • resourcemanager.projects.get
  • כדי לאחזר מפתח ציבורי: cloudkms.cryptoKeyVersions.viewPublicKey
  • כדי ליצור מפתחות HSM עם דייר יחיד:
    • cloudkms.singleTenantHsmInstances.get
    • cloudkms.singleTenantHsmInstances.use

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

יצירת מפתח הצפנה סימטרי

המסוף

  1. נכנסים לדף Key Management במסוף Google Cloud .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות שעבורו רוצים ליצור מפתח.

  3. לוחצים על Create key.

  4. בשדה Key name, מזינים שם למפתח.

  5. בשדה רמת הגנה, בוחרים באפשרות תוכנה, HSM או HSM עם דייר יחיד.

  6. אם בחרתם באפשרות Single-tenant HSM, בוחרים את המופע של Single-tenant HSM שבו רוצים ליצור את המפתח.

  7. בקטע Key material, בוחרים באפשרות Generated key.

  8. בשדה מטרה, בוחרים באפשרות הצפנה/פענוח סימטריים.

  9. מאשרים את ערכי ברירת המחדל של תקופת הרוטציה והתחלה בתאריך.

  10. לוחצים על יצירה.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

כדי ליצור מפתח תוכנה או מפתח Cloud HSM מרובה-דיירים, משתמשים בפקודה kms keys create:

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --protection-level "PROTECTION_LEVEL"

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • PROTECTION_LEVEL: רמת ההגנה שרוצים להשתמש בה עבור המפתח, לדוגמה software או hsm. אפשר להשמיט את הדגל --protection-level עבור מפתחות software.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

כדי ליצור מפתח Cloud HSM בדייר יחיד, מוסיפים את הדגל --crypto-key-backend לפקודה kms keys create:

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --protection-level "hsm-single-tenant" \
    --crypto-key-backend="projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"

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

  • INSTANCE_PROJECT: המזהה של הפרויקט שבו קיים מופע Cloud HSM עם דייר יחיד.
  • INSTANCE_NAME: השם של מופע Single-tenant Cloud HSM שבו רוצים ליצור את המפתח. מידע נוסף על מכונות Cloud HSM עם דייר יחיד זמין במאמר יצירה וניהול של מכונת Cloud HSM עם דייר יחיד.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


using Google.Cloud.Kms.V1;

public class CreateKeySymmetricEncryptDecryptSample
{
    public CryptoKey CreateKeySymmetricEncryptDecrypt(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-symmetric-encryption-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
// on Cloud KMS.
func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-symmetric-encryption-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %w", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import java.io.IOException;

public class CreateKeySymmetricEncryptDecrypt {

  public void createKeySymmetricEncryptDecrypt() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String id = "my-key";
    createKeySymmetricEncryptDecrypt(projectId, locationId, keyRingId, id);
  }

  // Create a new key that is used for symmetric encryption and decryption.
  public void createKeySymmetricEncryptDecrypt(
      String projectId, String locationId, String keyRingId, String id) 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 "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Build the symmetric key to create.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created symmetric key %s%n", createdKey.getName());
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-symmetric-encryption-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeySymmetricEncryptDecrypt() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
      },
    },
  });

  console.log(`Created symmetric key: ${key.name}`);
  return key;
}

return createKeySymmetricEncryptDecrypt();

PHP

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Google Cloud ולהתקין את Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;

function create_key_symmetric_encrypt_decrypt(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-symmetric-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
        );

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

from google.cloud import kms


def create_key_symmetric_encrypt_decrypt(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new symmetric encryption/decryption key in Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to create (e.g. 'my-symmetric-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    algorithm = (
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
    )
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created symmetric key: {created_key.name}")
    return created_key

Ruby

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id          = "my-symmetric-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:          :ENCRYPT_DECRYPT,
  version_template: {
    algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created symmetric key: #{created_key.name}"

API

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

כדי ליצור מפתח תוכנה או מפתח Cloud HSM מרובה-דיירים, משתמשים ב-method‏ CryptoKey.create:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'

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

  • PROJECT_ID: מזהה הפרויקט שמכיל את מחזיק המפתחות.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • KEY_NAME: השם של המפתח.
  • PROTECTION_LEVEL: רמת ההגנה של המפתח. לדוגמה: SOFTWARE או HSM.
  • ALGORITHM: אלגוריתם החתימה של HMAC – לדוגמה, HMAC_SHA256. כדי לראות את כל אלגוריתמי ה-HMAC הנתמכים, אפשר לעיין במאמר בנושא אלגוריתמים לחתימת HMAC.
כדי ליצור מפתח Cloud HSM בדיירות יחידה, מגדירים את PROTECTION_LEVEL ל-HSM_SINGLE_TENANT ומוסיפים את הדגל --crypto-key-backend לפקודה kms keys create:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "HSM_SINGLE_TENANT",
        "algorithm": "ALGORITHM",
        "crypto-key-backend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME" }}'

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

  • INSTANCE_PROJECT: המזהה של הפרויקט שבו קיים מופע Cloud HSM עם דייר יחיד.
  • INSTANCE_NAME: השם של מופע Single-tenant Cloud HSM שבו רוצים ליצור את המפתח. מידע נוסף על מכונות Cloud HSM עם דייר יחיד זמין במאמר יצירה וניהול של מכונת Cloud HSM עם דייר יחיד.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

יצירת מפתח הצפנה סימטרי עם רוטציה אוטומטית בהתאמה אישית

כשיוצרים מפתח, אפשר לציין את תקופת הרוטציה שלו, כלומר את הזמן שעובר בין היצירה האוטומטית של גרסאות מפתח חדשות. אפשר גם לציין באופן עצמאי את זמן הרוטציה הבא, כך שהרוטציה הבאה תתרחש מוקדם יותר או מאוחר יותר מתקופת רוטציה אחת מעכשיו.

המסוף

כשמשתמשים במסוף Google Cloud כדי ליצור מפתח, Cloud KMS מגדיר באופן אוטומטי את תקופת הרוטציה ואת זמן הרוטציה הבא. אפשר להשתמש בערכי ברירת המחדל או לציין ערכים אחרים.

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

  1. עבור תקופת רוטציית מפתחות, בוחרים באחת מהאפשרויות.

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

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_ROTATION_TIME

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • ROTATION_PERIOD: מרווח הזמן לרוטציה של המפתח. לדוגמה, 30d לרוטציה של המפתח כל 30 יום. תקופת הרוטציה צריכה להיות לפחות יום אחד ולכל היותר 100 שנים. למידע נוסף, ראו CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: חותמת הזמן שבה תסתיים הרוטציה הראשונה. לדוגמה: 2023-01-01T01:02:03. אפשר להשמיט את --next-rotation-time כדי לתזמן את הרוטציה הראשונה לתקופה של רוטציה אחת מהרגע שבו מריצים את הפקודה. מידע נוסף זמין במאמר CryptoKey.nextRotationTime.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;
using System;

public class CreateKeyRotationScheduleSample
{
    public CryptoKey CreateKeyRotationSchedule(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-key-with-rotation-schedule")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            },

            // Rotate the key every 30 days.
            RotationPeriod = new Duration
            {
                Seconds = 60 * 60 * 24 * 30, // 30 days
            },

            // Start the first rotation in 24 hours.
            NextRotationTime = new Timestamp
            {
                Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"
	"time"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// createKeyRotationSchedule creates a key with a rotation schedule.
func createKeyRotationSchedule(w io.Writer, parent, id string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-key-with-rotation-schedule"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},

			// Rotate the key every 30 days
			RotationSchedule: &kmspb.CryptoKey_RotationPeriod{
				RotationPeriod: &durationpb.Duration{
					Seconds: int64(60 * 60 * 24 * 30), // 30 days
				},
			},

			// Start the first rotation in 24 hours
			NextRotationTime: &timestamppb.Timestamp{
				Seconds: time.Now().Add(24 * time.Hour).Unix(),
			},
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %w", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.time.temporal.ChronoUnit;

public class CreateKeyRotationSchedule {

  public void createKeyRotationSchedule() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String id = "my-key";
    createKeyRotationSchedule(projectId, locationId, keyRingId, id);
  }

  // Create a new key that automatically rotates on a schedule.
  public void createKeyRotationSchedule(
      String projectId, String locationId, String keyRingId, String id) 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 "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Calculate the date 24 hours from now (this is used below).
      long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

      // Build the key to create with a rotation schedule.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))

              // Rotate every 30 days.
              .setRotationPeriod(
                  Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))

              // Start the first rotation in 24 hours.
              .setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created key with rotation schedule %s%n", createdKey.getName());
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-rotating-encryption-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyRotationSchedule() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
      },

      // Rotate the key every 30 days.
      rotationPeriod: {
        seconds: 60 * 60 * 24 * 30,
      },

      // Start the first rotation in 24 hours.
      nextRotationTime: {
        seconds: new Date().getTime() / 1000 + 60 * 60 * 24,
      },
    },
  });

  console.log(`Created rotating key: ${key.name}`);
  return key;
}

return createKeyRotationSchedule();

PHP

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Google Cloud ולהתקין את Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

function create_key_rotation_schedule(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-key-with-rotation-schedule'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION))

        // Rotate the key every 30 days.
        ->setRotationPeriod((new Duration())
            ->setSeconds(60 * 60 * 24 * 30)
        )

        // Start the first rotation in 24 hours.
        ->setNextRotationTime((new Timestamp())
            ->setSeconds(time() + 60 * 60 * 24)
        );

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created key with rotation: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

import time

from google.cloud import kms


def create_key_rotation_schedule(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new key in Cloud KMS that automatically rotates.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to create (e.g. 'my-rotating-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    algorithm = (
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
    )
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
        # Rotate the key every 30 days.
        "rotation_period": {"seconds": 60 * 60 * 24 * 30},
        # Start the first rotation in 24 hours.
        "next_rotation_time": {"seconds": int(time.time()) + 60 * 60 * 24},
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created labeled key: {created_key.name}")
    return created_key

Ruby

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id          = "my-key-with-rotation"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:            :ENCRYPT_DECRYPT,
  version_template:   {
    algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
  },

  # Rotate the key every 30 days.
  rotation_period:    {
    seconds: 60 * 60 * 24 * 30
  },

  # Start the first rotation in 24 hours.
  next_rotation_time: {
    seconds: (Time.now + (60 * 60 * 24)).to_i
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created rotating key: #{created_key.name}"

API

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

כדי ליצור מפתח, משתמשים ב-method‏ CryptoKey.create:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "PURPOSE", "rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'

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

  • PURPOSE: המטרה של המפתח.
  • ROTATION_PERIOD: מרווח הזמן לרוטציה של המפתח. לדוגמה, 30d לרוטציה של המפתח כל 30 יום. תקופת הרוטציה צריכה להיות לפחות יום אחד ולכל היותר 100 שנים. למידע נוסף, ראו CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: חותמת הזמן שבה תסתיים הרוטציה הראשונה. לדוגמה: 2023-01-01T01:02:03. מידע נוסף זמין במאמר CryptoKey.nextRotationTime.

הגדרת משך הזמן של המצב 'מתוכנן להשמדה'

כברירת מחדל, גרסאות של מפתחות ב-Cloud KMS נמצאות 30 ימים במצב של התקופה scheduled for destruction‏ (DESTROY_SCHEDULED) לפני שהן נמחקות. המצב 'מתוזמן להשמדה' נקרא לפעמים מצב מחיקה עם יכולת שחזור. אפשר להגדיר את משך הזמן שבו גרסאות המפתח נשארות במצב הזה, עם המגבלות הבאות:

  • אפשר להגדיר את משך הזמן רק במהלך יצירת המפתח.
  • אחרי שמציינים את משך הזמן של המפתח, אי אפשר לשנות אותו.
  • המשך חל על כל הגרסאות של המפתח שייווצרו בעתיד.
  • משך הזמן המינימלי הוא 24 שעות לכל המפתחות, חוץ ממפתחות לייבוא בלבד שמשך הזמן המינימלי שלהם הוא 0.
  • משך הזמן המקסימלי הוא 120 ימים.
  • משך הזמן שמוגדר כברירת מחדל הוא 30 יום.

יכול להיות שבארגון שלכם מוגדר ערך מינימלי של משך הזמן שנקבע למחיקה, בהתאם למדיניות הארגון. למידע נוסף, ראו שליטה במחיקת מפתחות.

כדי ליצור מפתח עם משך זמן מותאם אישית למצב מתוזמן להשמדה:

המסוף

  1. נכנסים לדף Key Management במסוף Google Cloud .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות שעבורו רוצים ליצור מפתח.

  3. לוחצים על Create key.

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

  5. לוחצים על הגדרות נוספות.

  6. בקטע משך הזמן של המצב 'מתוזמן להשמדה', בוחרים את מספר הימים שבהם המפתח יישאר במצב מתוזמן להשמדה לפני שהוא יושמד באופן סופי.

  7. לוחצים על Create key.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose PURPOSE \
    --destroy-scheduled-duration DURATION

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • PURPOSE: ייעוד המפתח, לדוגמה, encryption.
  • DURATION: משך הזמן שבו המפתח יישאר במצב scheduled for destruction לפני שהוא יושמד באופן סופי.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

מומלץ להשתמש בברירת המחדל של משך הזמן (30 ימים) לכל המפתחות, אלא אם יש לכם דרישות ספציפיות של אפליקציה או דרישות רגולטוריות שמחייבות ערך שונה.

יצירת מפתח אסימטרי

בקטעים הבאים מוסבר איך ליצור מפתחות אסימטריים.

יצירת מפתח פענוח אסימטרי

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

כשיוצרים את המפתח, הגרסה הראשונית של המפתח היא במצב בהמתנה ליצירה. כשהמצב משתנה למופעל, אפשר להשתמש במפתח. מידע נוסף על מצבי גרסה של מפתח זמין במאמר מצבי גרסה של מפתח.

המסוף

  1. נכנסים לדף Key Management במסוף Google Cloud .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות שעבורו רוצים ליצור מפתח.

  3. לוחצים על Create key.

  4. בשדה Key name, מזינים שם למפתח.

  5. בשדה Protection level, בוחרים באפשרות Software,‏ HSM או Single-tenant HSM.

  6. אם בחרתם באפשרות Single-tenant HSM, בוחרים את המופע של Single-tenant HSM שבו רוצים ליצור את המפתח.

  7. בקטע Key material, בוחרים באפשרות Generated key.

  8. בקטע מטרה, בוחרים באפשרות פענוח אסימטרי.

  9. בקטע Algorithm (אלגוריתם), בוחרים באפשרות 3072 bit RSA - OAEP Padding - SHA256 Digest (RSA של 3072 ביט – מילוי OAEP – תקציר SHA256). אפשר לשנות את הערך הזה בגרסאות עתידיות של המפתח.

  10. לוחצים על יצירה.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "asymmetric-encryption" \
    --default-algorithm "ALGORITHM" \
    --protection-level "PROTECTION_LEVEL"

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • ALGORITHM: האלגוריתם שבו יש להשתמש עבור המפתח, לדוגמה rsa-decrypt-oaep-3072-sha256. רשימת האלגוריתמים הנתמכים להצפנה אסימטרית מופיעה במאמר אלגוריתמים להצפנה אסימטרית.
  • PROTECTION_LEVEL: רמת ההגנה שרוצים להשתמש בה עבור המפתח.
אם רוצים ליצור את המפתח במופע של Cloud HSM עם דייר יחיד, משתמשים ברמת ההגנה hsm-single-tenant, מוסיפים את הדגל --cryptoKeyBackend ומציינים את מזהה המשאב של מופע Cloud HSM עם דייר יחיד שבו רוצים ליצור את המפתח:

--crypto-key-backend "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל ‏‎`--help` ‎.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class CreateKeyAsymmetricDecryptSample
{
    public CryptoKey CreateKeyAsymmetricDecrypt(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-asymmetric-encrypt-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaDecryptOaep2048Sha256,
            },

            // Optional: customize how long key versions should be kept before destroying.
            DestroyScheduledDuration = new Duration
            {
                Seconds = 24 * 60 * 60,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"
	"time"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/protobuf/types/known/durationpb"
)

// createKeyAsymmetricDecrypt creates a new asymmetric RSA encrypt/decrypt key
// pair where the private key is stored in Cloud KMS.
func createKeyAsymmetricDecrypt(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-asymmetric-encryption-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ASYMMETRIC_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_RSA_DECRYPT_OAEP_2048_SHA256,
			},

			// Optional: customize how long key versions should be kept before destroying.
			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %w", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import java.io.IOException;

public class CreateKeyAsymmetricDecrypt {

  public void createKeyAsymmetricDecrypt() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String id = "my-asymmetric-decryption-key";
    createKeyAsymmetricDecrypt(projectId, locationId, keyRingId, id);
  }

  // Create a new asymmetric key for the purpose of encrypting and decrypting
  // data.
  public void createKeyAsymmetricDecrypt(
      String projectId, String locationId, String keyRingId, String id) 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 "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Build the asymmetric key to create.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ASYMMETRIC_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256))

              // Optional: customize how long key versions should be kept before destroying.
              .setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24 * 60 * 60))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created asymmetric key %s%n", createdKey.getName());
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-asymmetric-decrypt-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyAsymmetricDecrypt() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ASYMMETRIC_DECRYPT',
      versionTemplate: {
        algorithm: 'RSA_DECRYPT_OAEP_2048_SHA256',
      },

      // Optional: customize how long key versions should be kept before
      // destroying.
      destroyScheduledDuration: {seconds: 60 * 60 * 24},
    },
  });

  console.log(`Created asymmetric key: ${key.name}`);
  return key;
}

return createKeyAsymmetricDecrypt();

PHP

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Google Cloud ולהתקין את Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Protobuf\Duration;

function create_key_asymmetric_decrypt(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-asymmetric-decrypt-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ASYMMETRIC_DECRYPT)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_DECRYPT_OAEP_2048_SHA256)
        )

        // Optional: customize how long key versions should be kept before destroying.
        ->setDestroyScheduledDuration((new Duration())
            ->setSeconds(24 * 60 * 60)
        );

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created asymmetric decryption key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

import datetime

# Import the client library.
from google.cloud import kms
from google.protobuf import duration_pb2  # type: ignore


def create_key_asymmetric_decrypt(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new asymmetric decryption key in Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to create (e.g. 'my-asymmetric-decrypt-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT
    algorithm = (
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256
    )
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
        # Optional: customize how long key versions should be kept before
        # destroying.
        "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
            datetime.timedelta(days=1)
        ),
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created asymmetric decrypt key: {created_key.name}")
    return created_key

Ruby

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id          = "my-asymmetric-decrypt-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:          :ASYMMETRIC_DECRYPT,
  version_template: {
    algorithm: :RSA_DECRYPT_OAEP_2048_SHA256
  },

  # Optional: customize how long key versions should be kept before destroying.
  destroy_scheduled_duration: {
    seconds: 24 * 60 * 60
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created asymmetric decryption key: #{created_key.name}"

API

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

יוצרים מפתח אסימטרי לפענוח באמצעות ה-method‏ CryptoKey.create.
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "ASYMMETRIC_DECRYPT", "protectionLevel": "PROTECTION_LEVEL", "versionTemplate": {"algorithm": "ALGORITHM"}}'

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

  • PROJECT_ID: מזהה הפרויקט שמכיל את מחזיק המפתחות.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • KEY_NAME: השם של המפתח.
  • ALGORITHM: האלגוריתם שבו רוצים להשתמש עבור המפתח, לדוגמה RSA_DECRYPT_OAEP_3072_SHA256. רשימה של אלגוריתמים נתמכים להצפנה אסימטרית זמינה במאמר בנושא אלגוריתמים להצפנה אסימטרית.
  • PROTECTION_LEVEL: רמת ההגנה שרוצים להשתמש בה עבור המפתח.
אם רוצים ליצור את המפתח ב-Cloud HSM עם דייר יחיד, מגדירים את PROTECTION_LEVEL ל-HSM_SINGLE_TENANT ומוסיפים את השדה cryptoKeyBackend לגוף הפקודה עם מזהה המשאב של מופע Cloud HSM עם דייר יחיד שאליו רוצים לייבא את המפתח:

"cryptoKeyBackend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"

יצירת מפתח אסימטרי לחתימה

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

כשיוצרים את המפתח, הגרסה הראשונית של המפתח היא במצב בהמתנה ליצירה. כשהמצב משתנה למופעל, אפשר להשתמש במפתח. מידע נוסף על מצבי גרסה של מפתח זמין במאמר מצבי גרסה של מפתח.

המסוף

  1. נכנסים לדף Key Management במסוף Google Cloud .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות שעבורו רוצים ליצור מפתח.

  3. לוחצים על Create key.

  4. בשדה Key name, מזינים שם למפתח.

  5. בשדה רמת הגנה, בוחרים באפשרות תוכנה, HSM או HSM עם דייר יחיד.

  6. אם בחרתם באפשרות Single-tenant HSM, בוחרים את המופע של Single-tenant HSM שבו רוצים ליצור את המפתח.

  7. בקטע Key material, בוחרים באפשרות Generated key.

  8. בקטע מטרה, בוחרים באפשרות חתימה אסימטרית.

  9. בקטע Algorithm (אלגוריתם), בוחרים באפשרות Elliptic Curve P-256 - SHA256 Digest (עקומת אליפטית P-256 – גיבוב SHA256). אפשר לשנות את הערך הזה בגרסאות עתידיות של המפתח.

  10. לוחצים על יצירה.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "asymmetric-signing" \
    --default-algorithm "ALGORITHM" \
    --protection-level "PROTECTION_LEVEL"

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • ALGORITHM: האלגוריתם שבו יש להשתמש עבור המפתח, לדוגמה, ec-sign-p256-sha256. רשימת האלגוריתמים הנתמכים מופיעה במאמר אלגוריתמים אסימטריים לחתימה.
  • PROTECTION_LEVEL: רמת ההגנה שרוצים להשתמש בה עבור המפתח.
אם רוצים ליצור את המפתח במופע של Cloud HSM עם דייר יחיד, צריך להגדיר את PROTECTION_LEVEL ל-hsm-single-tenant ולהוסיף את הדגל --cryptoKeyBackend כדי לציין את מזהה המשאב של מופע Cloud HSM עם דייר יחיד שבו רוצים ליצור את המפתח:

--crypto-key-backend "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל ‏‎`--help` ‎.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class CreateKeyAsymmetricSignSample
{
    public CryptoKey CreateKeyAsymmetricSign(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-asymmetric-signing-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricSign,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaSignPkcs12048Sha256,
            },

            // Optional: customize how long key versions should be kept before destroying.
            DestroyScheduledDuration = new Duration
            {
                Seconds = 24 * 60 * 60,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"
	"time"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/protobuf/types/known/durationpb"
)

// createKeyAsymmetricSign creates a new asymmetric RSA sign/verify key pair
// where the private key is stored in Cloud KMS.
func createKeyAsymmetricSign(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-asymmetric-signing-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ASYMMETRIC_SIGN,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
			},

			// Optional: customize how long key versions should be kept before destroying.
			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %w", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import java.io.IOException;

public class CreateKeyAsymmetricSign {

  public void createKeyAsymmetricSign() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String id = "my-asymmetric-signing-key";
    createKeyAsymmetricSign(projectId, locationId, keyRingId, id);
  }

  // Create a new asymmetric key for the purpose of signing and verifying data.
  public void createKeyAsymmetricSign(
      String projectId, String locationId, String keyRingId, String id) 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 "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Build the asymmetric key to create.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256))

              // Optional: customize how long key versions should be kept before destroying.
              .setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24 * 60 * 60))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created asymmetric key %s%n", createdKey.getName());
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-asymmetric-sign-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyAsymmetricSign() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ASYMMETRIC_SIGN',
      versionTemplate: {
        algorithm: 'RSA_SIGN_PKCS1_2048_SHA256',
      },

      // Optional: customize how long key versions should be kept before
      // destroying.
      destroyScheduledDuration: {seconds: 60 * 60 * 24},
    },
  });

  console.log(`Created asymmetric key: ${key.name}`);
  return key;
}

return createKeyAsymmetricSign();

PHP

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Google Cloud ולהתקין את Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Protobuf\Duration;

function create_key_asymmetric_sign(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-asymmetric-signing-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ASYMMETRIC_SIGN)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_SIGN_PKCS1_2048_SHA256)
        )

        // Optional: customize how long key versions should be kept before destroying.
        ->setDestroyScheduledDuration((new Duration())
            ->setSeconds(24 * 60 * 60)
        );

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created asymmetric signing key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.


import datetime

# Import the client library.
from google.cloud import kms
from google.protobuf import duration_pb2  # type: ignore


def create_key_asymmetric_sign(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new asymmetric signing key in Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to create (e.g. 'my-asymmetric-signing-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN
    algorithm = (
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256
    )
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
        # Optional: customize how long key versions should be kept before
        # destroying.
        "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
            datetime.timedelta(days=1)
        ),
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created asymmetric signing key: {created_key.name}")
    return created_key

Ruby

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id          = "my-asymmetric-signing-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:          :ASYMMETRIC_SIGN,
  version_template: {
    algorithm: :RSA_SIGN_PKCS1_2048_SHA256
  },

  # Optional: customize how long key versions should be kept before destroying.
  destroy_scheduled_duration: {
    seconds: 24 * 60 * 60
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created asymmetric signing key: #{created_key.name}"

API

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

יוצרים מפתח חתימה אסימטרי באמצעות הקריאה אל [`CryptoKey.create`](/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys/create).
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "ASYMMETRIC_SIGN", "versionTemplate": {"protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM"}}'

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

  • PROJECT_ID: מזהה הפרויקט שמכיל את מחזיק המפתחות.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • KEY_NAME: השם של המפתח.
  • PROTECTION_LEVEL: רמת ההגנה שרוצים להשתמש בה עבור המפתח.
  • ALGORITHM: האלגוריתם שבו רוצים להשתמש עבור המפתח, לדוגמה EC_SIGN_P256_SHA256. במאמר אלגוריתמים אסימטריים לחתימה תוכלו למצוא רשימה של אלגוריתמים נתמכים.

    ‫ אם רוצים ליצור את המפתח ב-Cloud HSM עם דייר יחיד, מגדירים את PROTECTION_LEVEL ל-HSM_SINGLE_TENANT, מוסיפים את השדה cryptoKeyBackend לגוף הפקודה ומוסיפים את מזהה המשאב של מופע Cloud HSM עם דייר יחיד שאליו רוצים לייבא את המפתח:

    "crypto-key-backend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"

יצירת מפתח KEM

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

כשיוצרים את המפתח, הגרסה הראשונית של המפתח היא במצב בהמתנה ליצירה. כשהמצב משתנה למופעל, אפשר להשתמש במפתח. מידע נוסף על מצבי גרסה של מפתח זמין במאמר מצבי גרסה של מפתח.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "key-encapsulation" \
    --default-algorithm "ALGORITHM"

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • ALGORITHM: האלגוריתם שבו יש להשתמש עבור המפתח, לדוגמה ml-kem-768. רשימה של אלגוריתמים נתמכים של אנקפסולציה של מפתחות זמינה במאמר אלגוריתמים של אנקפסולציה של מפתחות.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

API

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

יוצרים מפתח עם מטרה KEY_ENCAPSULATION על ידי קריאה ל-CryptoKey.create.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "KEY_ENCAPSULATION", "versionTemplate": {"algorithm": "ALGORITHM"}}'

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

  • PROJECT_ID: מזהה הפרויקט שמכיל את מחזיק המפתחות.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • KEY_NAME: השם של המפתח.
  • ALGORITHM: האלגוריתם שבו רוצים להשתמש עבור המפתח, לדוגמה ML_KEM_768. רשימה של אלגוריתמים נתמכים של אנקפסולציה של מפתחות זמינה במאמר אלגוריתמים של אנקפסולציה של מפתחות.

שליפת המפתח הציבורי

כשיוצרים מפתח אסימטרי, Cloud KMS יוצר זוג מפתחות ציבורי/פרטי. אפשר לאחזר את המפתח הציבורי של מפתח אסימטרי מופעל בכל שלב אחרי יצירת המפתח.

המפתח הציבורי הוא בפורמט PEM (דואר אלקטרוני עם פרטיות משופרת). למידע נוסף, אפשר לעיין בקטעים General Considerations ו-Textual Encoding of Subject Public Key Info ב-RFC 7468.

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

המסוף

  1. נכנסים לדף Key Management במסוף Google Cloud .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות שמכיל את המפתח האסימטרי שרוצים לאחזר את המפתח הציבורי שלו.

  3. לוחצים על שם המפתח שרוצים לאחזר את המפתח הציבורי שלו.

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

  5. לוחצים על קבלת מפתח ציבורי.

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

אם האפשרות Get public key לא מופיעה, צריך לוודא את הדברים הבאים:

  • המפתח הוא מפתח אסימטרי.
  • גרסת המפתח מופעלת.
  • יש לך הרשאה מסוג cloudkms.cryptoKeyVersions.viewPublicKey.

שם הקובץ של מפתח ציבורי שהורד ממסוף Google Cloud הוא מהצורה:

KEY_RING-KEY_NAME-KEY_VERSION.pub

כל חלק בשם הקובץ מופרד באמצעות מקף, לדוגמה ringname-keyname-version.pub.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys versions get-public-key KEY_VERSION \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --public-key-format PUBLIC_KEY_FORMAT \
    --output-file OUTPUT_FILE_PATH

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

  • KEY_VERSION: מספר גרסת המפתח.
  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • PUBLIC_KEY_FORMAT: הפורמט שבו רוצים לייצא את המפתח הציבורי. כדי להשתמש באלגוריתמים של NIST PQC (Preview), משתמשים ב-nist-pqc, וכדי להשתמש ב-X-Wing, משתמשים ב-xwing-raw-bytes. לכל שאר המפתחות, אפשר להשתמש בערך pem, der או להשמיט את הפרמטר הזה.
  • OUTPUT_FILE_PATH: הנתיב שבו רוצים לשמור את קובץ המפתח הציבורי, לדוגמה public-key.pub.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


using Google.Cloud.Kms.V1;

public class GetPublicKeySample
{
    public PublicKey GetPublicKey(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        PublicKey result = client.GetPublicKey(keyVersionName);

        // Return the ciphertext.
        return result;
    }
}

Go

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

import (
	"context"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"hash/crc32"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// getPublicKey retrieves the public key from an asymmetric key pair on
// Cloud KMS.
func getPublicKey(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.GetPublicKeyRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetPublicKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get public key: %w", err)
	}

	// The 'Pem' field is the raw string representation of the public key.
	// Convert 'Pem' into bytes for further processing.
	key := []byte(result.Pem)

	// Optional, but recommended: perform integrity verification on result.
	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
	// https://cloud.google.com/kms/docs/data-integrity-guidelines
	crc32c := func(data []byte) uint32 {
		t := crc32.MakeTable(crc32.Castagnoli)
		return crc32.Checksum(data, t)
	}
	if int64(crc32c(key)) != result.PemCrc32C.Value {
		return fmt.Errorf("getPublicKey: response corrupted in-transit")
	}

	// Optional - parse the public key. This transforms the string key into a Go
	// PublicKey.
	block, _ := pem.Decode(key)
	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return fmt.Errorf("failed to parse public key: %w", err)
	}
	fmt.Fprintf(w, "Retrieved public key: %v\n", publicKey)
	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.PublicKey;
import java.io.IOException;
import java.security.GeneralSecurityException;

public class GetPublicKey {

  public void getPublicKey() throws IOException, GeneralSecurityException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String keyVersionId = "123";
    getPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Get the public key associated with an asymmetric key.
  public void getPublicKey(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      throws IOException, GeneralSecurityException {
    // 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 "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Get the public key.
      PublicKey publicKey = client.getPublicKey(keyVersionName);
      System.out.printf("Public key: %s%n", publicKey.getPem());
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function getPublicKey() {
  const [publicKey] = await client.getPublicKey({
    name: versionName,
  });

  // Optional, but recommended: perform integrity verification on publicKey.
  // For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
  // https://cloud.google.com/kms/docs/data-integrity-guidelines
  const crc32c = require('fast-crc32c');
  if (publicKey.name !== versionName) {
    throw new Error('GetPublicKey: request corrupted in-transit');
  }
  if (crc32c.calculate(publicKey.pem) !== Number(publicKey.pemCrc32c.value)) {
    throw new Error('GetPublicKey: response corrupted in-transit');
  }

  console.log(`Public key pem: ${publicKey.pem}`);

  return publicKey;
}

return getPublicKey();

PHP

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Google Cloud ולהתקין את Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\GetPublicKeyRequest;

function get_public_key(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key',
    string $versionId = '123'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key version name.
    $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Call the API.
    $getPublicKeyRequest = (new GetPublicKeyRequest())
        ->setName($keyVersionName);
    $publicKey = $client->getPublicKey($getPublicKeyRequest);
    printf('Public key: %s' . PHP_EOL, $publicKey->getPem());

    return $publicKey;
}

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

from google.cloud import kms


def get_public_key(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.PublicKey:
    """
    Get the public key for an asymmetric key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        version_id (string): ID of the key to use (e.g. '1').

    Returns:
        PublicKey: Cloud KMS public key response.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    # Call the API.
    public_key = client.get_public_key(request={"name": key_version_name})

    # Optional, but recommended: perform integrity verification on public_key.
    # For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
    # https://cloud.google.com/kms/docs/data-integrity-guidelines
    if not public_key.name == key_version_name:
        raise Exception("The request sent to the server was corrupted in-transit.")
    # See crc32c() function defined below.
    if not public_key.pem_crc32c == crc32c(public_key.pem.encode("utf-8")):
        raise Exception(
            "The response received from the server was corrupted in-transit."
        )
    # End integrity verification

    print(f"Public key: {public_key.pem}")
    return public_key


def crc32c(data: bytes) -> int:
    """
    Calculates the CRC32C checksum of the provided data.
    Args:
        data: the bytes over which the checksum should be calculated.
    Returns:
        An int representing the CRC32C checksum of the provided bytes.
    """
    import crcmod  # type: ignore

    crc32c_fun = crcmod.predefined.mkPredefinedCrcFun("crc-32c")
    return crc32c_fun(data)

Ruby

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"
# version_id  = "123"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the key version name.
key_version_name = client.crypto_key_version_path project:            project_id,
                                                  location:           location_id,
                                                  key_ring:           key_ring_id,
                                                  crypto_key:         key_id,
                                                  crypto_key_version: version_id

# Call the API.
public_key = client.get_public_key name: key_version_name
puts "Public key: #{public_key.pem}"

API

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

שולפים את המפתח הציבורי באמצעות קריאה ל-method‏ CryptoKeyVersions.getPublicKey.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION/publicKey?public_key_format=PUBLIC_KEY_FORMAT" \
    --request "GET" \
    --header "authorization: Bearer TOKEN"

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

  • PROJECT_ID: מזהה הפרויקט שמכיל את מחזיק המפתחות.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • KEY_NAME: השם של המפתח.
  • KEY_VERSION: מספר גרסת המפתח.
  • PUBLIC_KEY_FORMAT: הפורמט שבו רוצים לייצא את המפתח הציבורי. עבור אלגוריתמים של PQC ‏(Preview), משתמשים ב-NIST_PQC. לכל שאר המפתחות, אפשר להשתמש ב-PEM או להשמיט את הפרמטר הזה.

אם משמיטים את פורמט המפתח הציבורי עבור מפתח שאינו PQC, הפלט דומה לזה:

{
  "pem": "-----BEGIN PUBLIC KEY-----\nQ29uZ3JhdHVsYXRpb25zLCB5b3UndmUgZGlzY292ZX
          JlZCB0aGF0IHRoaXMgaXNuJ3QgYWN0dWFsbHkgYSBwdWJsaWMga2V5ISBIYXZlIGEgbmlj
          ZSBkYXkgOik=\n-----END PUBLIC KEY-----\n",
  "algorithm": "ALGORITHM",
  "pemCrc32c": "2561089887",
  "name": "projects/PROJECT_ID/locations/LOCATION/keyRings/
           KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/
           KEY_VERSION",
  "protectionLevel": "PROTECTION_LEVEL"
}

עבור אלגוריתם PQC עם פורמט מפתח ציבורי NIST_PQC, הפלט דומה לזה שמוצג בהמשך:

{
  "publicKeyFormat": "NIST_PQC",
  "publicKey": {
    "crc32cChecksum": "1985843562",
    "data": "kdcOIrFCC5kN8S4i0+R+AoSc9gYIJ9jEQ6zG235ZmCQ="
  }
  "algorithm": "ALGORITHM",
  "name": "projects/PROJECT_ID/locations/LOCATION/keyRings/
           KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/
           KEY_VERSION",
  "protectionLevel": "PROTECTION_LEVEL"
}

המרת מפתח ציבורי לפורמט JWK

בעזרת Cloud KMS אפשר לאחזר מפתח ציבורי בפורמט PEM. יכול להיות שבאפליקציות מסוימות יידרשו פורמטים אחרים של מפתחות, כמו JSON Web Key ‏ (JWK). מידע נוסף על פורמט JWK זמין ב-RFC 7517.

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

Go

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

import (
	"context"
	"crypto/x509"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"hash/crc32"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"github.com/lestrrat-go/jwx/v2/jwk"
)

// getPublicKeyJwk retrieves the public key from an asymmetric key pair on Cloud KMS.
func getPublicKeyJwk(w io.Writer, cryptoKeyVersionName string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.GetPublicKeyRequest{
		Name: cryptoKeyVersionName,
	}

	// Call the API to get the public key.
	result, err := client.GetPublicKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get public key: %w", err)
	}

	// The 'Pem' field is the raw string representation of the public key.
	// Convert 'Pem' into bytes for further processing.
	key := []byte(result.Pem)

	// Optional, but recommended: perform integrity verification on result.
	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
	// https://cloud.google.com/kms/docs/data-integrity-guidelines
	crc32c := func(data []byte) uint32 {
		t := crc32.MakeTable(crc32.Castagnoli)
		return crc32.Checksum(data, t)
	}
	if int64(crc32c(key)) != result.PemCrc32C.Value {
		return fmt.Errorf("getPublicKey: response corrupted in-transit")
	}

	// Optional - parse the public key.
	// This transforms the string key into a Go PublicKey.
	block, _ := pem.Decode(key)
	_, err = x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return fmt.Errorf("failed to parse public key: %w", err)
	}

	// If all above checks pass, convert it into JWK format.
	jwkKey, err := jwk.ParseKey(key, jwk.WithPEM(true))
	if err != nil {
		return fmt.Errorf("Failed to parse the PEM public key: %w", err)
	}

	fmt.Fprintf(w, "The public key in JWK format: ")
	json.NewEncoder(w).Encode(jwkKey)
	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.PublicKey;
// NOTE: The library nimbusds is NOT endorsed for anything beyond conversion to JWK.
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.JWK;
import java.io.IOException;
import java.security.GeneralSecurityException;

public class ConvertPublicKeyToJwk {

  public void convertPublicKey() throws IOException, GeneralSecurityException, JOSEException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String keyVersionId = "123";
    convertPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // (Get and) Convert the public key associated with an asymmetric key.
  public void convertPublicKey(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      throws IOException, GeneralSecurityException, JOSEException {
    // 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 "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Get the public key and convert it to JWK format.
      PublicKey publicKey = client.getPublicKey(keyVersionName);
      JWK jwk = JWK.parseFromPEMEncodedObjects(publicKey.getPem());
      System.out.println(jwk.toJSONString());
    }
  }
}

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

from google.cloud import kms
from jwcrypto import jwk


def get_public_key_jwk(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.PublicKey:
    """
    Get the public key of an asymmetric key in JWK format.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        version_id (string): ID of the key to use (e.g. '1').

    Returns:
        PublicKey: Cloud KMS public key response.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    # Call the API.
    public_key = client.get_public_key(request={"name": key_version_name})

    # Optional, but recommended: perform integrity verification on public_key.
    # For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
    # https://cloud.google.com/kms/docs/data-integrity-guidelines
    if not public_key.name == key_version_name:
        raise Exception("The request sent to the server was corrupted in-transit.")
    # See crc32c() function defined below.
    if not public_key.pem_crc32c == crc32c(public_key.pem.encode("utf-8")):
        raise Exception(
            "The response received from the server was corrupted in-transit."
        )
    # End integrity verification

    # Convert to JWK format.
    jwk_key = jwk.JWK.from_pem(public_key.pem.encode())
    return jwk_key.export(private_key=False)


def crc32c(data: bytes) -> int:
    """
    Calculates the CRC32C checksum of the provided data.
    Args:
        data: the bytes over which the checksum should be calculated.
    Returns:
        An int representing the CRC32C checksum of the provided bytes.
    """
    import crcmod  # type: ignore

    crc32c_fun = crcmod.predefined.mkPredefinedCrcFun("crc-32c")
    return crc32c_fun(data)

שליטה בגישה למפתחות אסימטריים

כדי להשתמש בחותם או במאמת, צריך לקבל את ההרשאה או התפקיד המתאימים במפתח האסימטרי.

  • למשתמש או לשירות שיבצעו חתימה, מעניקים את ההרשאה cloudkms.cryptoKeyVersions.useToSign במפתח האסימטרי.

  • כדי שמשתמש או שירות יוכלו לאחזר את המפתח הציבורי, צריך להעניק להם את ההרשאה cloudkms.cryptoKeyVersions.viewPublicKey במפתח האסימטרי. המפתח הציבורי נדרש לאימות החתימה.

מידע על הרשאות ותפקידים בגרסה של Cloud KMS זמין במאמר הרשאות ותפקידים.

יצירת מפתח חתימה של MAC

המסוף

  1. נכנסים לדף Key Management במסוף Google Cloud .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות שעבורו רוצים ליצור מפתח.

  3. לוחצים על Create key.

  4. בשדה Key name, מזינים שם למפתח.

  5. בשדה רמת הגנה, בוחרים באפשרות תוכנה, HSM או HSM עם דייר יחיד.

  6. אם בחרתם באפשרות Single-tenant HSM, בוחרים את המופע של Single-tenant HSM שבו רוצים ליצור את המפתח.

  7. בקטע Key material, בוחרים באפשרות Generated key.

  8. בשדה Purpose, בוחרים באפשרות MAC signing/verification.

  9. אופציונלי: ב-Algorithm, בוחרים אלגוריתם לחתימת HMAC.

  10. לוחצים על יצירה.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

כדי ליצור מפתח תוכנה או מפתח Cloud HSM רב-דיירים, משתמשים בפקודה kms keys create:

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "mac" \
    --default-algorithm "ALGORITHM" \
    --protection-level "PROTECTION_LEVEL"

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • ALGORITHM: אלגוריתם החתימה של HMAC – לדוגמה, hmac-sha256. כדי לראות את כל אלגוריתמי ה-HMAC הנתמכים, אפשר לעיין במאמר בנושא אלגוריתמים לחתימת HMAC.
  • PROTECTION_LEVEL: רמת ההגנה של המפתח, לדוגמה hsm. אפשר להשמיט את הדגל --protection-level עבור software מפתחות.

כדי לראות את כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

כדי ליצור מפתח Cloud HSM בדייר יחיד, מוסיפים את הדגל --crypto-key-backend לפקודה kms keys create:

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "mac" \
    --default-algorithm "ALGORITHM" \
    --protection-level "PROTECTION_LEVEL" \
    --crypto-key-backend="projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"

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

  • INSTANCE_PROJECT: המזהה של הפרויקט שבו קיים מופע Cloud HSM עם דייר יחיד.
  • INSTANCE_NAME: השם של מופע Single-tenant Cloud HSM שבו רוצים ליצור את המפתח. מידע נוסף על מכונות Cloud HSM עם דייר יחיד זמין במאמר יצירה וניהול של מכונת Cloud HSM עם דייר יחיד.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class CreateKeyMacSample
{
    public CryptoKey CreateKeyMac(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-mac-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.Mac,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.HmacSha256,
            },

            // Optional: customize how long key versions should be kept before destroying.
            DestroyScheduledDuration = new Duration
            {
                Seconds = 24 * 60 * 60,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"
	"time"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/protobuf/types/known/durationpb"
)

// createKeyMac creates a new key for use with MacSign.
func createKeyMac(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-mac-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_MAC,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_HMAC_SHA256,
			},

			// Optional: customize how long key versions should be kept before destroying.
			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %w", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import java.io.IOException;

public class CreateKeyMac {

  public void createKeyMac() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String id = "my-mac-key";
    createKeyMac(projectId, locationId, keyRingId, id);
  }

  // Create a new key for use with MacSign.
  public void createKeyMac(String projectId, String locationId, String keyRingId, String id)
      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 "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Build the mac key to create.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.MAC)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.HMAC_SHA256))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created mac key %s%n", createdKey.getName());
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-mac-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyMac() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'MAC',
      versionTemplate: {
        algorithm: 'HMAC_SHA256',
      },

      // Optional: customize how long key versions should be kept before
      // destroying.
      destroyScheduledDuration: {seconds: 60 * 60 * 24},
    },
  });

  console.log(`Created mac key: ${key.name}`);
  return key;
}

return createKeyMac();

PHP

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Google Cloud ולהתקין את Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Protobuf\Duration;

function create_key_mac(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-mac-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::MAC)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::HMAC_SHA256)
        )

        // Optional: customize how long key versions should be kept before destroying.
        ->setDestroyScheduledDuration((new Duration())
            ->setSeconds(24 * 60 * 60)
        );

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created mac key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.


import datetime

from google.cloud import kms
from google.protobuf import duration_pb2  # type: ignore


def create_key_mac(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new key in Cloud KMS for HMAC operations.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to create (e.g. 'my-mac-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.MAC
    algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.HMAC_SHA256
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
        # Optional: customize how long key versions should be kept before
        # destroying.
        "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
            datetime.timedelta(days=1)
        ),
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created mac key: {created_key.name}")
    return created_key

Ruby

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id          = "my-mac-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:          :MAC,
  version_template: {
    algorithm: :HMAC_SHA256
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created mac key: #{created_key.name}"

API

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

כדי ליצור מפתח תוכנה או מפתח Cloud HSM מרובה-דיירים, משתמשים ב-method‏ CryptoKey.create:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "MAC", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'

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

  • PROJECT_ID: מזהה הפרויקט שמכיל את מחזיק המפתחות.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • KEY_NAME: השם של המפתח.
  • PROTECTION_LEVEL: רמת ההגנה של המפתח, לדוגמה SOFTWARE או HSM.
  • ALGORITHM: אלגוריתם החתימה של HMAC, לדוגמה HMAC_SHA256. כדי לראות את כל אלגוריתמי ה-HMAC הנתמכים, אפשר לעיין במאמר בנושא אלגוריתמים לחתימת HMAC.

כדי ליצור מפתח Cloud HSM בדייר יחיד, מוסיפים את השדה cryptoKeyBackend לגוף הבקשה CryptoKey.create:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "MAC", "versionTemplate": {
      "protectionLevel": "PROTECTION_LEVEL",
      "algorithm": "ALGORITHM",
      "cryptoKeyBackend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME" }}'

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

  • INSTANCE_PROJECT: המזהה של הפרויקט שבו קיים מופע Cloud HSM עם דייר יחיד.
  • INSTANCE_NAME: השם של מופע Single-tenant Cloud HSM שבו רוצים ליצור את המפתח. מידע נוסף על מכונות Cloud HSM עם דייר יחיד זמין במאמר יצירה וניהול של מכונת Cloud HSM עם דייר יחיד.

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