יצירת מפתח

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

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

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

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

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

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

כדי לקבל את ההרשאות שדרושות ליצירת מפתחות, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-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 במסוף Cloud de Confiance .

    כניסה אל Key Management

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

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

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

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

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

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

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

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

gcloud

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

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

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

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

  • KEY_NAME: השם של המפתח.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום ב-Cloud KMS שבו נמצא אוסף המפתחות.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --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 ב- Cloud de Confiance ולהתקין את 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.

כדי ליצור מפתח תוכנה, משתמשים ב-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": "SOFTWARE", "algorithm": "ALGORITHM" }}'

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

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

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

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

המסוף

כשמשתמשים במסוף Cloud de Confiance כדי ליצור מפתח, 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 ב- Cloud de Confiance ולהתקין את 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 במסוף Cloud de Confiance .

    כניסה אל 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 במסוף Cloud de Confiance .

    כניסה אל Key Management

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

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

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

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

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

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

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

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

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: רמת ההגנה שרוצים להשתמש בה עבור המפתח.
כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל ‏‎`--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;
    }
}